user1867391
user1867391

Reputation:

Swapping Div Content & CSS Using jQuery & AJAX

I am trying to use jQuery & AJAX to replace the content of a div with content of a thumbnail div. Right now I have a featured section which has specific styling for its h2, h3 and p tags, as well as its video.

The thumbnails have the same markup as far as h2, h3, p tags and a video but each with their own specific css styling.

What I'm looking to do is on click of one of the thumbnails, it replaces the feature section with the information of the thumbnail and then puts the featured section down within the thumbnails.

I have it somewhat started but I can't seem to remove and add classes to the specific thumbnail without actually changing the css of the thumbnail below either.

Any help would be greatly appreciated.

I have created a jsfiddle with my current set up and what I have so far.

http://jsfiddle.net/drewbietron/YstAQ/

$(document).ready(function(){
   $("#one.promo-item").click(function(e){
       e.preventDefault();
       var content = $(this).html();
       $('.video-container-featured').replaceWith('<div class="video-container-promo" id="one">' +content+ '</div>'),
       $('#one.video-container-promo').addClass('.video-container-featured');
     });
 });

Thank you!

Upvotes: 4

Views: 1108

Answers (1)

joemaller
joemaller

Reputation: 20576

Generally, you've got a lot more code than you need, to do what you want to do. Think simple and remember that child nodes inherit specificity from their parents.

You've got this:

<div class="promo-item" id="one">
    <div class="video-container-promo" id="one"><iframe src="#"></iframe></div>
    <h2>title...</h2>
    [...]

As mentioned above, you can't have duplicate ids. But even if you could, the nested id="one" is completely redundant. You would target that element with #one .video-container-promo. Likewise, you can target any nested child by starting your css selector with #one. (As an aside, numerically indexed items can be acessed in jQuery with the eq() method, no need to clutter your markup.)

Once you clean up your html, your jQuery code can essentially become a one-liner. To swap out the contents of one div with the contents of a clicked div, just do this:

$('.source'​​​​​).click(function(){
    $('#target').children().replaceWith($(this).clone().children());
});

The target, based on your example should probably be an id. The only other consideration is to be sure the element heirarchies you're slinging around match up.

Here's a simple jsfiddle showing how this might work: http://jsfiddle.net/joemaller/qxUvp/

Upvotes: 1

Related Questions