My Technical Notes

Monday, 4 February 2013

Waiting for an Element to be injected using Javascript/JQuery

Imagine that we wanted to insert a paragraph button in the Blogger Toolbar, situtating it before the bold button using GreaseMonkey. So from this:

to this:

Before we write any code, we need to first determine whether we can grab the bold button element because we want to use jQuery's .insertBefore() function to insert the new paragraph button before the bold button. We write some code to test whether we can remove the bold button:


$(function() {
 $('div#bold').remove();
});

But what we notice is that the above code does not remove the bold button. Why? Because the element has not been inserted into the page when our code has executed. We need to wait for the element to appear in the DOM before we can remove it. For this we use setTimeout:


function removeBoldButton() {
 if ($('div#bold').length) {
  $('div#bold').remove();
 } else {
  setTimeout(removeBoldButton, 30);
 }
}

$(function() {
 removeBoldButton();
});

No comments: