0

I have some results that are loaded via Ajax in the #results container and anothers, the same content in #last_results (this one loads without ajax). The same scripts that work on #last_results doesnt work in #results I think due to they are not binded.

HTML

 <ul id="results"></ul>

     <ul id="last_results">
                    <li class=showLb>[click to show LightBox]</li>
                    <li class=showLb>[click to show LightBox]</li>
                    <li class=showLb>[click to show LightBox]</li>
    </ul>

JQUERY This is a basic Jquery script:

   $('.showLb').on('click',function(e){
           alert('Show LightBox');

       });

This script works in the page li but not in the loaded via Ajax li. I knew I have to delegate or use on, How

joe
  • 69
  • 1
  • 2
  • 11

2 Answers2

0

Here you go. Now, My preference would be to ask you to actually go and check what this change does. Remember, we are here to help you understand.

$('.results').on('click', '.showLb' ,function(e){
        alert('Show LightBox');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="results"></ul>

     <ul id="last_results">
                    <li class=showLb>[click to show LightBox]</li>
                    <li class=showLb>[click to show LightBox]</li>
                    <li class=showLb>[click to show LightBox]</li>
    </ul>
Liam
  • 27,717
  • 28
  • 128
  • 190
Akshay Khandelwal
  • 1,570
  • 11
  • 19
0

You have to define your on click method directly after you execute you ajax call.

$.ajax({
...
success: funtion(data){
       //your code
       $('.showLb').on('click',function(e){ alert('Show LightBox'); });
}
...
Flex Code
  • 21
  • 7
  • Don't do this. this is wrong. You should add attach the `on` to a static element not try and rebind in the success call back – Liam Mar 12 '18 at 14:46