Welcome to WebmasterWorld Guest from 54.166.31.252

Forum Moderators: open

Message Too Old, No Replies

getting #ID of a clickable via jQuery

     
6:34 pm on Mar 21, 2013 (gmt 0)

Preferred Member

10+ Year Member

joined:Nov 10, 2005
posts: 387
votes: 0


How do I grab the CSS #ID of the clicked element below, so that I can execute subsequent commands on it:

<div id="ID1" onclick="clickable">Div 1</div>
<div id="ID2" onclick="clickable">Div 2</div>
<div id="ID3" onclick="clickable">Div 3</div>

Using script:

function clickable() {
// need to grab '#ID1','#ID2', or '#ID3' depending on which is clicked
}

I tried simply using $(this)... but it doesn't work.
12:47 am on Mar 22, 2013 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
posts:1585
votes: 0


<div id="ID1" onclick="clickable(this)">Div 1</div>
...

function clickable(el) {
alert(el.id); // gives ID1
}

Note that when onclick is set his way (as opposed to within javascript) the value must be a statement

onclick="clickable" BAD
onclick="clickable()" OK
onclick="clickable(this)" OK
onclick="alert(this.id)" OK
1:19 pm on Mar 22, 2013 (gmt 0)

Preferred Member

10+ Year Member

joined:Nov 10, 2005
posts:387
votes: 0


Great, thanks. Glad I asked -- never would have gotten that on my own.

Just to follow up, the only way I could get el.id to work in a jQuery command was to use:

$("#" + el.id).show();

Is that the only/best way to code it? Seems a little complex for a simple var.
11:42 pm on Mar 22, 2013 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
posts:1585
votes: 0


For that you do not need to get the id or even give it an id in the first place.

$(el).show();
5:06 pm on Mar 23, 2013 (gmt 0)

Preferred Member

10+ Year Member

joined:Nov 10, 2005
posts:387
votes: 0


Ouch -- that was easy.

My javascript ignorance is showing. Some day I'll be able to afford a professional programmer to do my website. Until then, you guys are life savers.

Many thanks, DaveVk.
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members