Michel Joanisse
Michel Joanisse

Reputation: 460

jQuery + A function that returns clicked element

I've been stuck on this for a long time now, I am looking for a bit of guidance ... I want to turn the following, into something more dynamic. I want the 'selector' to change / be based on whichever element was clicked.

So this is kind of what I think needs to be done:

  1. figure out which element was clicked. (h1, p, ol)
  2. with that element now in a variable, apply a similar function to the one i've created below..

Otherwise, I have to specify this same function for every element instance. (h1, h2, h3, p, ul, ol)

So far this is what I have: (which works, but evidently only for my h1 element)

$("#content_body h1").click(function() {    
        $(this).hide(); //hide current element.
        $(this).next().show(); //display next element.

        var numofEl = $("#content_body h1").length;

        if ($(this).next().index() == numofEl) { //if we're at last element,
        $("h1:first-child").show(); //restart cycle.
        }
});

Any help is always very much appreciated.. Thanks in advance!

*Update**

Another way of putting this / describe what I'm trying to get at:

Say you have many different elements in a container. (eg > #content_body)

Upvotes: 0

Views: 151

Answers (4)

pif
pif

Reputation: 96

is this what you want?

var length = $("#content_body").children().length;
$("#content_body").children().each(function(index){

$(this).click(function() {    
$(this).hide(); //hide current element.
$(this).next().show(); //display next element.


if (length-1 == index) { //if we're at last element,
$("h1:first-child").show(); //restart cycle.
}
});
 });

Upvotes: 0

Rafay
Rafay

Reputation: 31043

have a look at jquery multiple selectors

you can do it a couple of ways like

$("h1,p,ol,div").bind("click",function(){

//write the generic code here
});

also (as suggested by 8vius)

$('h1,p,ol,div').click(function(){ 
//write the generic code here
})

inside the handler you can access the clicked element by $(this) or this

here is the fiddle http://jsfiddle.net/6gCRF/

Upvotes: 1

marissajmc
marissajmc

Reputation: 2603

You can make the function dynamic like this:

showHide('h1');
showHide('p');
showHide('ol');

function showHide(element){

    $(element).click(function() {    
            $(element).hide(); //hide current element.
            $(element).next().show(); //display next element.

            var numofEl = $(element).length;

            if ($(element).next().index() == numofEl) { //if we're at last element,
            $(element).eq(0).show(); //restart cycle.
            }
    });
}

Upvotes: 0

8vius
8vius

Reputation: 5836

You can comma separate your selector if you want to apply it to several different DOM elements:

$('h1,p,ol').click(function(){ })

Upvotes: 1

Related Questions