Reputation: 3255
So, I'm new to Jquery and I want to know why this happens:
$('Button').click(bunz2);
function bunz2(){
$('body').css({"background-color":"yellow","font-size":"200%"});
}
This is my button defined in HTML:
<button id="myButton" type="button">Click Me!</button>
This works, but the second I change my code to, it no longer works. :
$('myButton').click(bunz2);
function bunz2(){
$('body').css({"background-color":"yellow","font-size":"200%"});
}
Why?
Upvotes: 1
Views: 73
Reputation: 19529
You need the id
attribute selector #
:
$('#myButton').click(...);
That tells jQuery "select the element that has the unique 'id' attribute 'myButton'". In your first example, $('Button')
tells jQuery "select all button elements on the page". That's because, without the leading #
it's a more generic selector. For example $('div')
would select all <div>
elements.
Cheers
Upvotes: 5
Reputation: 4168
The $('button')
active for all button
tag ,
if you must select id you can use :
$("#myButton").click(bunz2);
#
is ID symbol and .
is class symbol ...
Upvotes: 2
Reputation: 129
When you put $('Button').click(bunz2);
you refer to all the buttons of the page. To refer specifically to a button, you should use the ID. In Jquery you should put $.('#myButton').click(
)
Upvotes: 3
Reputation: 359776
$('myButton')
looks for elements with tag name myButton
, not ID myButton
. Change
$('myButton').click(bunz2);
to
$('#myButton').click(bunz2);
Read:
Upvotes: 1