Reputation: 73
I am new to this and I can't seem to get the jQuery to load. I am trying to toggle the class on an item identified by id.
The goal is to have the clicked item to have the class "menu-selected' and the item to have the class "unselected"
I believe I've placed all the relevant HTML below. It may be that I've made a mistake in my HTML or CSS, though it is working no differently than before I attempted to add JS.
Did I import jQuery incorrectly?
Did I write the script correctly?
Is my order of operations/placement correct?
Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#left-cafe').click(function(){
$('#left-cafe').removeClass('unselected');
$('#left-cafe').addClass('menu-selected');
$('#left-breakfast').removeClass('menu-selected');
$('#left-breakfast').addClass('unselected');
});
});
</script>
<style>
.left-menu{
background-color:rgb(200,200,200);
display:block;
float:left;
width:100%;
height:50px;
}
.left-menu-list{
width:100%;
height:100%;
}
.left-menu-list li{
display:block;
float:left;
width:20%;
height:100%;
font-size:35px;
line-height:75px;
}
.menu-selected{
background-color:rgb(150,150,150);
}
.unselected{
display:none;
}
</style>
</head>
<body>
<div class="left-menu"> <!-- Start left-menu -->
<ul class="left-menu-list">
<li class="menu-selected" id="left-cafe">Cafe</li>
<li class="unselected" id="left-breakfast">Breakfast</li>
</ul>
</div> <!-- End left-menu -->
</body>
</html>
Upvotes: 1
Views: 66
Reputation: 3015
There's a problem in your script: just replace your JAVASCRIPT code with this code:
$(document).ready(function () {
$('#left-cafe,#left-breakfast').click(function () {
$(".menu-selected").removeClass("menu-selected").addClass("unselected");
$(this).addClass("menu-selected");
});
});
Upvotes: 0
Reputation: 18566
Your code doesn't have any jQuery error. But there is logic error.
$(document).ready(function(){
$('#left-cafe').click(function(){
$('#left-cafe').toggleClass(' menu-selected unselected');
$('#left-breakfast').toggleClass(' menu-selected unselected');
});
});
.left-menu {
background-color:rgba(200, 200, 200,1);
display:block;
float:left;
width:100%;
height:50px;
}
.left-menu-list {
width:100%;
height:100%;
}
.left-menu-list li {
display:block;
float:left;
width:20%;
height:100%;
font-size:35px;
line-height:75px;
}
.menu-selected {
background-color:rgba(150, 150, 150, 1);
}
.unselected {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body>
<div class="left-menu">
<!-- Start left-menu -->
<ul class="left-menu-list">
<li class="menu-selected" id="left-cafe">Cafe</li>
<li class="unselected" id="left-breakfast">Breakfast</li>
</ul>
</div>
You are trying to remove and add same class again. So there is no difference in your output. Instead you must toggle the class.
Upvotes: 3