27th November 2011 · By Lee Jacobson

Binding a click function to an element with an updating class

If you're dynamically updating an elements class with Javascript you will find your JQuery events binded to that elements class won't work.

JQuery offers a way to easily deal with this problem. If you're using a version of JQuery pre 1.7 the easiest way to do this is with the .live() function. Using the following code will attach the event for elements that match the selection currently and in the future.

$('.exampleClass.').live('click', function(){
  alert('You clicked me!');
});

Although this will work in JQuery 1.7 onwards, it's not recommended as better methods have been implemented. For example to do the above code in JQuery 1.7 you should use the following code:

$(document).on("click", '.exampleClass', function(){
  alert('You clicked me!');
});

This code could be used for something similar to the following example:

<html>
<head>
  <style type="text/css">
    .red{
      color:#f00;
    }
    .blue{
      color:#00f;
    }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<body>
<script>
$(document).on("click", ".red, .blue", function(){
  $(this).toggleClass("red blue");
});

</script>

<a class="red">Change color</a>
</body>
</html>


Author

Lee JacobsonHello, I'm Lee.
I'm a developer from the UK who writes about technology and startups. Here you'll find articles and tutorials about things that interest me. If you want to hire me or know more about me head over to my about me page

Social Links

Related Articles

Comments

blog comments powered by Disqus