this simple code is not working, just trying to add a class once clicked on.
$('a').click(function(){
//alert('on'); WORKING
$(this).addClass('on');
})
The HTML is simply..
<ul>
<li><a href="">List Item 1</li>
<li><a href="">List Item 2</li>
<li><a href="">List Item 3</li>
<li><a href="">List Item 4</li>
</ul>
this simple code is not working, just trying to add a class once clicked on.
$('a').click(function(){
//alert('on'); WORKING
$(this).addClass('on');
})
The HTML is simply..
<ul>
<li><a href="">List Item 1</li>
<li><a href="">List Item 2</li>
<li><a href="">List Item 3</li>
<li><a href="">List Item 4</li>
</ul>
Share
Improve this question
asked Aug 1, 2013 at 17:33
TopTomatoTopTomato
5853 gold badges8 silver badges24 bronze badges
4
- 2 Add return false; inside click handler? – Rake36 Commented Aug 1, 2013 at 17:35
- Do you have the jquery.js in the html file as resource? – dominic Commented Aug 1, 2013 at 17:35
-
Could also be missing the ready event:
$(function() { /* attach click event to dom elements here */ }
– David Sherret Commented Aug 1, 2013 at 17:38 - yes, it's in the jQuery document.ready handler – TopTomato Commented Aug 1, 2013 at 20:11
7 Answers
Reset to default 5You didn't ever close your <a>
, but it's working for me otherwise.
http://jsfiddle/L3nyE/
<ul>
<li><a href="#">List Item 1</a></li>
<li><a href="#">List Item 2</a></li>
<li><a href="#">List Item 3</a></li>
<li><a href="#">List Item 4</a></li>
</ul>
CSS:
.on { background-color:red; }
jQuery:
$('a').click(function(){
//alert('on'); WORKING
$(this).addClass('on');
});
Prevent the default behaviour
$('a').click(function(event){
event.preventDefault();
$(this).addClass('on');
});
Works for me, provided you either change the target of the links to "#"
. (Or return false
from the click handler.)
http://jsfiddle/jaNCq/1/
You never close your <a>
's but Firefox is smart enough to close them for you. Can't say for other browsers though.
Your code working fine, check so you load your code when the dom is loaded and ready. Working example
$(document).ready(function(){
$('a').click(function(){
$(this).addClass('on');
});
});
Don't forget to close your "a" tags. Also add a ";" at the end of your jQuery function.
Make sure you have the jquery lib referenced and wrap your code in the dom ready. This worked for me.
<style>
.on{
color:red;
}
</style>
<script>
$(function () {
$('a').click(function () {
//alert('on'); WORKING
$(this).addClass('on');
})
});
</script>
Your HTML is Incorrect
<ul>
<li><a href="#">List Item 1</a></li>
<li><a href="#">List Item 2</a></li>
<li><a href="#">List Item 3</a></li>
<li><a href="#">List Item 4</a></li>
Demo