How to identify the new element added in the select box/drop down menu dynamically using javascript/jquery

Hi,

I would like to know the event name for a selectbox/drop down when new element get added. This will help me to take a next action.

We have a dropdown which have 10 fixed element, there is a child window. User when click on particular link that item get added in the parent window drop down.

Now, we want to fire an event on addition of new element in drop down, please let me know the approach/event

Thanks in advance.

I think you basically have two options: either you can dispatch an event every time you’re adding a new item to the select element, or you can use a mutation observer to watch the select element for changes of its child nodes:

var target = document.getElementById('my-select'),
    event = new Event('select:add'),
    observer = new MutationObserver(function() {
        console.log('Mutation observer says hello!');
    }),
    config = {
        childList: true
    };

// observe
observer.observe(target, config);    

// listen
target.addEventListener('select:add', function() {
    console.log('Event listener says hello!');
});

document.getElementById('add-item').addEventListener('click', function() {
    var newItem = document.createElement('option');
  
    newItem.textContent = 'baz';
    target.appendChild(newItem);

    target.dispatchEvent(event);
});

fiddle

You’re thinking about this backwards, you don’t want to try and detect when your code modifies the select, you just want to call some other function in the event listener you already have.

myMagicLink.addEventListener('click', function(event) {
  // Add <option> to select
  // call some other function
})

Edit: Oops, sorry I missed the important part of the question that you’re modifying a parent document. You may want to look at postMessage in addition to the events mentioned above.

MutationObserver is deprecated so will likely go away.

Huh, didn’t know about that. Don’t you mean mutation events?

Oh, maybe I am getting confused there.

Phew! :-D

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.