Peter Boomsma
Peter Boomsma

Reputation: 9806

jQuery selector question

I'm working with an jQuery script that has gotten me pretty far but I kind of hit a mountain I can't seem to fix.

On this jsFiddle I simulated the problem : http://jsfiddle.net/nRD4L/2/

So this is the script I'm using, it enables me to click on a span and give it an function which is fine. The problem is a bit with the selector because the way it works now is that it selects the next div after the span to perform that function but due to some styling I can't have that div next to the span, it has to be a few elements before it.

jQuery(document).ready(function() {
jQuery('.social_media_updates_extended_view').hide();

jQuery(".wrapper_update_extend span").css('cursor', 'pointer').click(function() {
    var $this = $(this);
    $('.social_media_updates_extended_view').not($this.next("div")).fadeOut(200);
    $this.next("div").fadeToggle(200);
    });

});

I made an example on jsFiddle : On this jsFiddle I simulated the problem : http://jsfiddle.net/nRD4L/2/ here you should be able to see the problem. There are 4 span elements that are clickable but only the bottom two work because the div is next to the span but I need to find a way to make the top two div's to work the same like the bottom ones.

Upvotes: 1

Views: 87

Answers (3)

Andrea Colleoni
Andrea Colleoni

Reputation: 6021

Instead of selecting the next div in the dom, you can select an element by its id attribute using the # selector (like in CSS).

So if you give an id to the html element you want to fadeToggle() for example a DIV element:

<div id='myDiv'>The div's content</div>;

Then you can fadeToggle() with:

$('#myDiv').fadeToggle(200);

Assuming you can set element's ids through server side processing, you can consider define ids in couples.

You can see it work at http://jsfiddle.net/nRD4L/14/.

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206477

working DEMO jsFiddle

code used:

$('.social_media_updates_extended_view').hide();
$('.btnFadeIn').css('cursor', 'pointer');

$(".btnFadeIn").click(function() {    
    var $this = $(this);    
    if ( $this.hasClass('active')){return;}

    $('.social_media_updates_extended_view').fadeTo(300, 0);
    $('.active').removeClass('active');
    $this.addClass('active').parents('.wrapper_update').find('.social_media_updates_extended_view').fadeTo(300, 1);    
});

Upvotes: 1

Sotiris
Sotiris

Reputation: 40096

add this $this.parent(".wrapper_update_extend").siblings(".social_media_updates_extended_view").fadeToggle(200);

under $this.next("div").fadeToggle(200);

The above will select the parent .wrapper_update_extend and then the sibling .social_media_updates_extended_view

Check more for parent() & siblings().

Demo: http://jsfiddle.net/nRD4L/4/

Upvotes: 1

Related Questions