0

I want to use the same javascript function on more than 1 button , but it does not work. here is:

HTML

<a href="#" id="buton"><p> SOMETHING</p></a>
<a href="#" id="buton"><p> OTHERS</p></a>

<div id="link" style="display:none;">
    <h1>SOMETHING</h1>
</div>
<div id="link" style="display:none;">
    <h1>OTHERS</h1>
</div>

and JAVASCRIPT

<script>
$('#buton').click(function() {
$('#link').toggle('slow', function() {
// Animation complete.
});
});
</script>

so on the first buton it does work, but on the second one ( OTHERS ) it does not work. Why? and how can I fix that? ( I am about to use more than 10 buttons on my original page, so please give me the best idea )

1
  • 1.) ID attribute must be unique, hence your HTML is invalid. 2.) You can set a class attribute for all the buttons and set the event handler in the JS like $(".buttonclass").click(... Commented Apr 17, 2013 at 16:31

2 Answers 2

4

IDs MUST be unique.

You should try using a class instead.

HTML

<a href="#" class="buton" data-for="link1"><p> SOMETHING</p></a>
<a href="#" class="buton" data-for="link2"><p> OTHERS</p></a>

<div id="link1" style="display:none;">
    <h1>SOMETHING</h1>
</div>
<div id="link2" style="display:none;">
    <h1>OTHERS</h1>
</div>

and JAVASCRIPT

<script>
$('.buton').click(function() {
  $('#'+this.getAttribute("data-for")).toggle('slow', function() {
    // Animation complete.
  });
});
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

instead of getAttribute("data-for"), you can use the jquery data() function: $(this).data('for');
jQuery will create an internal cache (.data() expando property) after the first call to .data() that retrieves the data attribute value. Murder all the unicorns.
so there is no way putting a general statement instead of link1,link2..... ? cause if I create (for example ) 10 buttons, and then I eliminate the 4th and 5th I would have to modify all of them (from 6-10)
The numbers don't matter, what matters is that each data-for link has a corresponding element with that ID.
0

In HTML ids must be unique. The browser enforces this by returning only one result for #link.

You can either give them different ids or use a class.

$("#link1,#link2,#link3").toggle(..)

or

$(".links").toggle(..)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.