skip to Main Content

I’d like to hide an element that is inserted/injected to my Shopify store with an external app. It appears about a second later after everything has finished loading on the site and has a class called “hidethis” and a bunch of other elements.

This did not work and I have no idea what else to try.

$(".hidethis").hide();

I’m trying to hide this element based on the location of the user in the following manner:

 jQuery.ajax( {
  url: '//api.ipstack.com/check?access_key=xxx&fields=country_code',
  type: 'POST',
  dataType: 'jsonp',
  success: function(location) {



    if (location.country_code === 'EE') {


  $(function() {
  // if geolocation suggest you need to hide, execute this as soon as possible
  var sheet = window.document.styleSheets[0];
  sheet.insertRule('.cart__options { display:none; }', sheet.cssRules.length);




})

  } 
 }
} );

4

Answers


  1. Best solution: CSS

    .hidethis { display:none }
    

    If this is not possible and you need JS

      var sheet = window.document.styleSheets[0];
      sheet.insertRule('.hidethis { display:none; }', sheet.cssRules.length);
    
    $(function() {
      // if geolocation suggest you need to hide, execute this as soon as possible
      var sheet = window.document.styleSheets[0];
      sheet.insertRule('.hidethis { display:none; }', sheet.cssRules.length);
    
    
      // test code - remove this when you insert the above code in your page
      setTimeout(function() {$("#container").append('<div class="hidethis">Hide this</div>');}, 1000);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="container"></div>

    which translates to your Ajax example:

    $.ajax({
      url: '//api.ipstack.com/check?access_key=xxx&fields=country_code',
      type: 'POST',
      dataType: 'jsonp',
      success: function(location) {
        if (location.country_code === 'EE') {
          var sheet = window.document.styleSheets[0];
          sheet.insertRule('.hidethis { display:none; }', sheet.cssRules.length);
        }
      }
    })
    

    Alternatively add a

    <style>.hidethis { display:none }</style> 
    

    to the page before where the content you want to hide is going to appear. Then in your ajax do

    if (location.country_code != 'EE') { $(".hidethis").show() }
    

    You can also try an interval

    $(function() {
      var tId = setInterval(function() {
        var $hide = $(".hidethis");
        if ($hide.length>0) {
          clearInterval(tId);
          $hide.hide();
        }      
      },500);
    
    
      // test code - remove this when you insert the script in your page
      setTimeout(function() { $("#container").append('<div class="hidethis">Hide this</div>'); },1000);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="container"></div>
    Login or Signup to reply.
  2. Here an example how to add events:
    https://stackoverflow.com/a/48745137/155077

    functional equivalent to jQuery .on.

    Instead of adding an event-handler, you’ll just have to hide it.

    subscribeEvent(".feed", "click", ".feed-item", function (event) { /* here comes code of click-event*/ });
    

    The whole thing works with MutationObserver:

    // Options for the observer (which mutations to observe)
    let config = { attributes: false, childList: true, subtree: true };
    
    // Create an observer instance linked to the callback function
    let observer = new MutationObserver(callback);
    
    // Start observing the target node for configured mutations
    observer.observe(nodeToObserve, config);
    

    where callback:

    // Callback function to execute when mutations are observed
    let callback:MutationCallback = function (
        mutationsList: MutationRecord[], 
        observer: MutationObserver)
    {
        for (let mutation of mutationsList)
        {
            // console.log("mutation.type", mutation.type);
            // console.log("mutation", mutation);
    
            if (mutation.type == 'childList')
            {
                for (let i = 0; i < mutation.addedNodes.length; ++i)
                {
                    let thisNode: Node = mutation.addedNodes[i];
                    allDescendants(thisNode); // here you do something with it
                } // Next i 
    
            } // End if (mutation.type == 'childList') 
            // else if (mutation.type == 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.');
    
        } // Next mutation 
    
    }; // End Function callback 
    
    Login or Signup to reply.
  3. 1 : at first , you inspect in your browser and find the element
    2 : use $(document).ready() and hide that element

    Login or Signup to reply.
  4. Your problem isn’t actually about an element being added by an external app, the problem is that when your code to hide the element is executed the element isn’t on the DOM yet. Because the element is being added sometime later after all your JavaScript code was already executed.

    So, you have to execute your code after the element is added. One way to do that is by using MutationObserver.

    Here is a simple example using as referece the example in MDN:

    <div id="some-id"></div>
    
    // Select the node that will be observed for mutations
    const targetNode = document.getElementById('some-id');
    
    // Options for the observer (which mutations to observe)
    const config = { childList: true, subtree: true };
    
    // Callback function to execute when mutations are observed
    const callback = function(mutationsList, observer) {
        for(let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                document.querySelector('.hide').style.display = 'none';
            }
        }
    };
    
    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(callback);
    
    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);
    
    // Add a timeout to simulate JavaScript being executed after all your code was executed.
    setTimeout(() => {
        document.getElementById('some-id').innerHTML = '<span class="hide">Hello world</span>';
    }, 1000);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search