Reputation: 175
I'm trying to perform some style changes to list elements. This is what i'm trying to do... I have two lists, one is shopping items, the other is a list that helps manage the shopping items (set priority by changing background color of shopping list item). What i want to do is first click on a shopping item then click on one of the manage items to set some styling. I have something up and running, but it needs some work. One issue is if i go to manage (style) a second item on the list with a different priority, it applies the styling that all items the have been previously styled.
Do the following to see what i mean. Click on Bread, then click on high priority to change the background color of bread to read. Now click on Chips and then click on medium priority to change the background color to black. You'll now see that bread has now changed to black. Not good.
I'm sure the code is bloated, and could probably use some if/else logic instead of using nesting and completely separate function for each styling event. Sorry, posted by another newbie.
here is a fiddle
<div class="the-lst">
<h4>YOUR LIST - Click one of these items first</h4>
<ul id="sortable2" class="connectedSortable">
<li>Bread</li>
<li>Chips</li>
<li>Cookies</li>
</ul>
</div>
<div class="lst-manage">
<h4>MANAGE LIST - Then click one of these items to set priority</h4>
<ul>
<li id="hp">High Priority</li>
<li id="mp">Medium Priority</li>
<li id="lp">Low Priority</li>
<li id="done">Done</li>
<li id="remove">Remove</li>
</ul>
</div>
$(document).ready(function() {
$(".the-lst").on("click", "li", function(event) {
var lst = $(this).closest('li');
$('.lst-manage').on("click", "#hp",function(event) {
lst.css({'background-color': 'red'});
});
});
$(".the-lst").on("click", "li", function(event) {
var lst = $(this).closest('li');
$('.lst-manage').on("click", "#mp",function(event) {
lst.css({'background-color': 'black'});
});
});
$(".the-lst").on("click", "li", function(event) {
var lst = $(this).closest('li');
$('.lst-manage').on("click", "#lp",function(event) {
lst.css({'background-color': 'green'});
});
});
});
Upvotes: 0
Views: 142
Reputation: 207861
I'd reduce it to:
$('#sortable2 li').click(function () {
$('#sortable2 li').removeClass('selected');
$(this).addClass('selected');
})
$('.lst-manage li').click(function () {
if (this.id == "hp") $("#sortable2 li.selected").css('background', 'red')
if (this.id == "mp") $("#sortable2 li.selected").css('background', 'black')
if (this.id == "lp") $("#sortable2 li.selected").css('background', 'green')
})
Upvotes: 1