PinoyTech.org

CodeIgniter, Kohana, Mootools, jQuery and CSS

Using JQuery Live Events

Posted by teejay on April 22, 2009

jQuery 1.3 was released a few months ago but I really didn't try out the changes, especially the live event.

As I was digging into my everyday work, I needed to clone some markup. Unfortunately, click events only work on currently matched events. Here's how I fixed it.

The Problem

    <label for="file">File</label>
    <input type="text" name="file[]" id="file"  class="file" value=""/>
    <img src="media/images/search"/>
    <label for="caption">Caption</label>
    <textarea rows="3" cols="50" name="caption"></textarea>
    </div>
 $('img.pointer').click(function(){
  window.open('http://google.com, 'search_engine', 'height=500, width=600');
 });

I've modified the code to be as simple as possible and it works. Unfortunately this only works for currently matched elements like in the next sample

    <label for="file">File</label>
    <input type="text" name="file[]" id="file"  class="file" value=""/>
    <img src="media/images/search"/>
    <label for="caption">Caption</label>
    <textarea rows="3" cols="50" name="caption"></textarea>
    </div>
                                <a href="#" id="add_more">Add More Upload Boxes</a>
 $('img.pointer').click(function(){
  window.open('http://google.com, 'search_engine', 'height=500, width=600');
 });
 $('#add_more').click(function(e){
  e.preventDefault();
  $(this).prev('div.file').clone().insertAfter($(this).prev());
 });

This won't work. But here's a solution.

 $('img.pointer').live('click', function(){
  window.open('http://google.com, 'search_engine', 'height=500, width=600');
 });
 $('#add_more').click(function(e){
  e.preventDefault();
  $(this).prev('div.file').clone().insertAfter($(this).prev());
 });

Modifying the code to use the live event would automatically bind all current and future matched elements.

I've found this quite useful and certainly saved my life.

Categories: How To, Web Development

Tags: javascript, jquery

No Comments

Comments