0

I use ajax on my site for navigation but I'm having a problem with script tags in my pages. (My app is a Rails app but I don't think that makes a difference)

For example, I have a button on my page:

<button id="alert">click here</button>

and at the bottom:

<script>
    $("#alert").click(function() {
        alert("hi there")}
    );
</script>

The first time I go to the page, the button works fine. Then, I click around a few links on my Ajax site, go back to the page called with Ajax, and it doesn't work anymore. I heard before 'Ajax strips out the tags' or something, but haven't come up with a solution.

Would eval() work? Heard it might do it. How would I implement? I've been working at this for days now and it seems strange there's no simple work around.

5
  • Can you please explain why you simply can't use event delegation. Commented May 18, 2013 at 1:29
  • does that script tag and its content get generated again each time that ajax page is called? Commented May 18, 2013 at 1:29
  • When you click around your ajax site do you rewrite the html? replace content? switching to .on would bind the listener to the window so even if the #alert element was added back in it would register. Commented May 18, 2013 at 1:29
  • @Jonathan Chow - I have several pages with script tags, with different info in each one. So yes, I suppose the tag and content get generated again each time. Commented May 18, 2013 at 1:43
  • @ChristopheHarris have you tried wrapping $(document).ready around? Commented May 18, 2013 at 2:25

1 Answer 1

4

Delegate your events

$(document).on('click', "#alert",function()
      {alert("hi there")}
 });

ideally it is better if you do not bind the events to the Document. Try binding the event to the closest possible static element.

Sign up to request clarification or add additional context in comments.

2 Comments

Not sure how this is a solution. Because for your code to work it has to be between script tags, so I still have the same problem.
Do you mean putting the code in a separate .js file? This wouldn't work for me because I also have dynamic variables, and they don't get reloaded with ajax from a .js file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.