Here you can see the when I click on the icon it doesn't change. How to change it
$(document).ready(function(){
$('.fa fa-bars').click(function(){
$(this).toggleClass('fa fa-times');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<script src="java.js"></script>
<script src="https://use.fontawesome.com/16ca663e5d.js"></script>
</head>
<body>
<header >
<nav >
<ul >
<li>
<a >Home</a>
</li>
<li >
<a>Gallery</a>
</li>
<li >
<a >Contact</a>
</li>
<li>
<a >Sign in</a>
</li>
</ul>
</nav>
<i class="fa fa-bars ham" aria-hidden="true"></i>
</header>
<section id="home" class="container-fluid">
</section>
<script>
$(document).ready(function(){
$('.fa fa-bars').click(function(){
$(this).toggleClass('fa fa-times');
});
});
</script>
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
As I mentioned in the comment, you have to change $('.fa fa-bars')
to $('.fa.fa-bars')
and then your toggleClass should look like .toggleClass('fa-bars fa-times')
$(document).ready(function() {
$('.fa.fa-bars').click(function() {
$(this).toggleClass('fa-bars fa-times');
});
});
Problem is that $('.fa fa-bars')
means that you are looking for an element with the class fa
and you are looking for a child of that element of the type fa-bars
, if that existed it would look like <fa-bars></fa-bars>
Demo
$(document).ready(function() {
$('.fa.fa-bars').click(function() {
$(this).toggleClass('fa-bars fa-times');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<script src="java.js"></script>
<script src="https://use.fontawesome.com/16ca663e5d.js"></script>
</head>
<body>
<header>
<nav>
<ul>
<li>
<a>Home</a>
</li>
<li>
<a>Gallery</a>
</li>
<li>
<a>Contact</a>
</li>
<li>
<a>Sign in</a>
</li>
</ul>
</nav>
<i class="fa fa-bars ham" aria-hidden="true"></i>
</header>
<section id="home" class="container-fluid">
</section>
<script>
$(document).ready(function() {
$('.fa fa-bars').click(function() {
$(this).toggleClass('fa fa-times');
});
});
</script>
</body>
</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I did some changes to your code now it's working. you must follow this link toggle class concept to properly understand toggle class how to work.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script>
$(document).ready(function () {
$(".fa-bars").click(function(e){
$(this).toggleClass("fa-bars fa-times"); //you can list several class names
});
});
</script>
</head>
<body>
<i class="fa fa-bars"></i>
</body>
</html>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>