Zoidik
Zoidik

Reputation: 91

JQuery show/hide whithout hard coded id

I wanna make jQuery function to show/hide some elements (now it is <li>);

So, I have this code:

.sub {
    display: none;
}

 ....

$(function show_sub(id) {
    $('#'+id).show('fast');
});

 .....

<a href="" onmouseover="show_sub('id1')" onclick="return false;"> Here is it </a> 
<li id="id1" class="sub"> .... </li>

On the Internet, I only found functions where I must hard code the id of the element.

I know my jQuery function is incorrect.

Please, help me!

Upvotes: 0

Views: 127

Answers (4)

emrahbasman
emrahbasman

Reputation: 2013

You can try the code below

html

<a href="#" class="li-toggler" data-toggle="id1">li toggler</a>   
<li id="id1">sometext</li>​

js

$("a.li-toggler").click(function() {
   $("#"+$(this).attr("data-toggle")).toggleClass("sub");
});

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

You could clean a bit your code doing like so

Html

<a href="#"> Here is it </a> 
<li class="sub"> .... </li>

Javascript

$(function() {
    $('a[href="#"]')
       .on('hover', function() {
           $(this).next('li').show('fast'); // or toggle();
       })
       .on('click', function(ev) {
           ev.preventDefault()
       })
});

Doing so you can avoid useless markup, redundant information and inline handlers.

Example Fiddle: http://jsfiddle.net/GYye8/

Upvotes: 4

Mikael H&#228;rsj&#246;
Mikael H&#228;rsj&#246;

Reputation: 1036

$("li.sub").show() shows all li's with class sub.

Is that what you´re after?

Upvotes: 0

Ari
Ari

Reputation: 3127

You need to get element you want to show/hide. Getting it by id is one way, but there are many more.

Look at jquery selectors.

For example you can show element with "sub" class by:

$(".sub").show();

Upvotes: 1

Related Questions