Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying an onclick event to an element that doesn't exist on page load

I have styled a list to look like a select box and I want to fire a function when the user clicks an element in the list however the element is loaded via AJAX and hence isn't there when the page loads and I can't bind an onclick event to it onDomReady.

If I had it as a normal select list I could just tag on an onChange event to the <select> field, but I obviously can't do that in my case.

My HTML:

<div id="main_category_field" class="fields">
    <div class="cat_list">
        <ul>
            <li class=""><a rel="1866" href="#1866">Sports Cards &gt;</a></li>
            <li class=""><a rel="1867" href="#1867">Gaming Cards &gt;</a></li>
            <li class=""><a rel="1868" href="#1868">Non-Sport Cards &gt;</a></li>
            <li class=""><a rel="1869" href="#1869">Supplies &amp; Storage &gt;</a></li>
            <li class=""><a rel="1940" href="#1940">Video Games </a></li>
        </ul>
    </div>
    <div class="contentClear"></div>
</div>

How can I run a function whenever the user clicks any of these options? Also would be great if you could also advise how to pass the respective value of the rel back when they click an option.

Using jQuery so options in that would be preferred.

Edit: Meant to say that the main element main_category_field is a static element. The elements inside are loaded via AJAX.

like image 465
Brett Avatar asked Dec 07 '22 03:12

Brett


1 Answers

you need to delegate your elements to static parent , if the element is added dynamically using on() try this

  $(document).on('click','li a',function(e){
    e.preventDefault();
    var rel = this.rel;
     //or using attr()
    var rel=$(this).attr('rel'); 
     alert(rel);  
  });

however delegating it to its closest static parent(present at a time of insertion) is better than document itself.. so if you are adding the list inside main_category_field div.. then you can use

    $('#main_category_field').on('click','li a',function(e){     
         //same stuff
like image 93
bipen Avatar answered Dec 31 '22 14:12

bipen