0

Say I have the following HTML

<div class="row">
  <div class="link grey">
    <a href="#">Link</a>
  </div>
</div>
<div class="row">
  <div class="link">
    <a href="#">Link</a>
  </div>
</div>
<div class="row">
  <div class="link">
    <a href="#">Link</a>
  </div>
</div>
<div class="row">
  <div class="link grey">
    <a href="#">Link</a>
  </div>
</div>

I want to be able to click the link, have the background colour change and have that state retained on ajax success (ajax call happens when the link is clicked). But right now, on ajax success, the previous sate shows up.

On success, I'm calling the function which handles the event

function ajaxOnSuccess(data) {
$(document).ready(function(){
    $('a').on('click', function(){
    $(this).closest('.link').toggleClass('grey');
  });
});
}

JSFiddle: http://jsfiddle.net/mzg2zk48/

zer0
  • 4,657
  • 7
  • 28
  • 49
  • Where's your ajax call? – TbWill4321 Dec 11 '15 at 17:03
  • there are two ways. first: reinit the eventlistener like calling a function after ajax call `function myFunction() { $('a').on('click', ..`. second: use `$(document).on('click', 'a', function(...` and catch the click event on document. – Chris Dec 11 '15 at 17:05
  • @Chris I think I'm doing the first method you mentioned here. I didn't understand the second. – zer0 Dec 11 '15 at 17:10
  • You must assign a class name to the clicked element in the success response. Toggling an element will assign the class name to the element but this i not persistent, so after the success (maybe the page is reloaded, I don't know) and the element has no class attached to it. It will help if you post also your ajax call o we cn see how you are handle this. – Franco Dec 11 '15 at 17:15
  • may you like to read [this](http://stackoverflow.com/questions/14879168/document-onclick-id-function-vs-id-onclick-function) about event delegation. it's very practicable. – Chris Dec 11 '15 at 17:15

1 Answers1

1

I think your javascript should be like following. Hope this will help.

$(document).ready(function(){
    $('a').on('click', function(){
        //ajax call goes here
        //ajax successs call ajaxOnSuccess(this) function
    });

    function ajaxOnSuccess(elm) {
        $(elm).closest('.link').toggleClass('grey');
    }  
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55