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
Best solution: CSS
If this is not possible and you need JS
which translates to your Ajax example:
Alternatively add a
to the page before where the content you want to hide is going to appear. Then in your ajax do
You can also try an interval
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.
The whole thing works with MutationObserver:
where callback:
1 : at first , you inspect in your browser and find the element
2 : use $(document).ready() and hide that element
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: