awakekat
awakekat

Reputation: 1

jQuery function breaks with .load

I am able to successfully load contents from a page called test.html into page called page.htm with:

$(document).ready(function(){ 
     $("#reveal").load("test.html");
});

I put an empty div in the page.htm called #reveal and the contents load - no problem.

In test.html I have two divs classes designated article titles and article contents with classes: .artTitle and .artContent. In page.html's css file, I have display:hidden the .artContent - so that all that shows is the .artTitles. I then want to reveal the .artContents by a toggle click.

I am able to get this jQuery process to work inline (in the same page) but breaks when loading the html. What is the problem when loading that I am missing - (very green newbie)?

Upvotes: 0

Views: 267

Answers (3)

Evan
Evan

Reputation: 11

Alright, I'm no expert with jQuery. In fact I came here hoping for a definitive answer to essentially the same question. The answers already given helped point me in the right direction... Here was my solution...

I'm assuming that you have some jquery function that looks something along the lines of,

 $('.trigger').click(function() { $('.artContents').toggle(); });

The HTML being loaded via .load() contains the .trigger to be clicked that will toggle .artContents , yes? Try,

$(document).on('click','.trigger', function() { $('.artContents').toggle(); });

I really hope that helps. I'm right there with you in the "very green newbie" camp, but this worked for me. I couldn't explain exactly why it works. Perhaps someone else can.

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

You need to use live event like following:

$('body').on('click', '.artTitles', function() { // binding live click to upcoming elements
   var self = this; // keeping reference to clicked title, because this will not catch into the hide callback function due to different scope
   $('.artContents:visible').hide( // hiding visible contents
    function() { // callback function
      $(self).closest('.artContents').show(300); // show content corresponding to title
   });
});

Upvotes: 0

Greg Pettit
Greg Pettit

Reputation: 10830

It's the toggle function that's likely the culprit, not the load function. Chances are you are binding to an element that does not exist until the content load. You need to use the delegate syntax of on() in order to bind a listener to #reveal or another ancestor.

Upvotes: 1

Related Questions