Reputation: 279
I have a list with a defined list-style-image and hover so as every time the user goes through the list, the image changes.
That's ok. What i would like to do is that when the user clicks on the item, the clicked item changes to another image accordingly either selected or not.
So far this is my code: JSFiddle
CSS
#FavListApp {
list-style-image: url('../images/FavStarUnSel.png');
list-style-position: inside;
cursor: pointer;
}
ul li:hover { list-style-image: url('../images/FavStarSel.png'); }
HTML
<ul id="FavListApp">
<li style="margin-bottom:20px;"><a href="#">Dragon App</a></li>
<li style="margin-bottom:20px;"><a href="#">Calculator</a></li>
<li style="margin-bottom:20px;"><a href="#">Brain Academy</a></li>
<li style="margin-bottom:20px;"><a href="#">Root Words</a></li>
</ul>
JQUERY
$(document).ready(function() {
$('#FavListApp li > a').click(function(){
$(this).parent().find('#FavListApp').css('listStyleImage','url(../images/FavStarUnSel.png)')
});
});
Upvotes: 0
Views: 1814
Reputation: 177692
My suggestion
$('#FavListApp li > a').on("click",function (e) {
e.preventDefault();
$link = $(this);
$link.toggleClass("selected");
$link.parent().css('listStyleImage', $link.hasClass("selected")?sel:unsel);
});
Upvotes: 2
Reputation: 13939
What about this :
(EDIT : Added toggle)
var selectedImage = 'url(../images/FavStarSel.png)'
var unselectedImage = 'url(../images/FavStarUnSel.png)'
$('#FavListApp li > a').click(function(){
//Remember current state
var li = $(this).parent()
var currentImage = li.css('listStyleImage')
//Revert all items to default image
$("#FavListApp li").css("list-style-image", unselectedImage);
//Toggle current selected li image
if (currentImage === selectedImage){
li.css('listStyleImage', unselectedImage)
}
else{
li.css('listStyleImage', selectedImage)
}
});
Upvotes: 0
Reputation: 13939
Oh just thought of a CSS trick.
Basically, you have a links that have just a "#" href, why not make point them to an ID (even if it doesn't exist ?)
Dragon App Calculator Brain Academy Root WordsThen make ue of the CSS :active
property
#FavListApp {
list-style-image: url('../images/FavStarUnSel.png');
list-style-position: inside;
cursor: pointer;
}
ul li:hover, ul li:active { list-style-image: url('../images/FavStarSel.png'); }
Upvotes: 0
Reputation: 15393
Use closest
in this context
$('#FavListApp li > a').click(function(){
$(this).closest('li').css('listStyleImage','url(../images/FavStarUnSel.png)')
});
Upvotes: 1