The "when page loads" part of the code works fine.
The "When selection is made" part of the code works but seems to stop after a couple of selection changes. Would like it to work on both select boxes as many times as the user changes the selections.
https://jsfiddle.net/czqpkL6j/1/
//when page loads
setTimeout(function() {
var iframePreLoad = $("#product-component-1635439141053").children().contents();
iframePreLoad.find(".shopify-buy__option-select__select").ready(function(){
iframePreLoad.find('select[name=Color] option:nth-child(1)').html('Black');
iframePreLoad.find('select[name=Color] option:nth-child(2)').html('Green');
});
//When selection is made
iframePreLoad.find('select').on('change', function() {
setTimeout(function() {
iframePreLoad.find('select[name=Color] option:nth-child(1)').html('Black');
iframePreLoad.find('select[name=Color] option:nth-child(2)').html('Green');
},100)
console.log('selection changed');
});
}, 3000);
CodePudding user response:
Not sure what's the surrounding here exactly but a wild guess based on experience: do the elements potentially change after the iframePreLoad.find(..)
selector resolved? If so, nodes matching the selector won't be in the result set (for obvious reasons) and thus have no change
handler attached.
The usual approach to problems like this is to make use of event bubbling and attach the listener to a container surrounding the elements you want to observe. That way you will catch events even from elements changed or added afterwards.