How do I select an element by it's toggled class in Javascript?

Viewed 68

Hey I have what seems to be a simple problem, but having some trouble. I want to only display an alert message once when I hit the X of my hamburger toggle menu. Any help is appreciated.

Here is the code I have in my codepen that I am referencing: https://codepen.io/toshvelaga/pen/wLJYKL

I have tried using the code below, but I get the alert message twice and also when clicking on the hamburger instead of just ONLY the X.

$(document).ready(function(){
    $('#nav-icon3').click(function(){
        $(this).toggleClass('open');

        $('#nav-icon3.open').click(function() {
            alert("hello");
        });
    });
});
2 Answers

Check whether the element has the open class in the (single) handler, and if it does, log the hello:

$('#nav-icon3').click(function() {
  if (this.matches('.open')) {
    console.log("hello");
  }
  $(this).toggleClass('open');
});
/* Icon 3 */

#nav-icon3 {
  width: 60px;
  height: 45px;
  position: relative;
  margin: 50px auto;
  -webkit-transform: rotate(0deg);
  -moz-transform: rotate(0deg);
  -o-transform: rotate(0deg);
  transform: rotate(0deg);
  -webkit-transition: .5s ease-in-out;
  -moz-transition: .5s ease-in-out;
  -o-transition: .5s ease-in-out;
  transition: .5s ease-in-out;
  cursor: pointer;
}

#nav-icon3 span {
  display: block;
  position: absolute;
  height: 9px;
  width: 100%;
  background: #d3531a;
  border-radius: 9px;
  opacity: 1;
  left: 0;
  -webkit-transform: rotate(0deg);
  -moz-transform: rotate(0deg);
  -o-transform: rotate(0deg);
  transform: rotate(0deg);
  -webkit-transition: .25s ease-in-out;
  -moz-transition: .25s ease-in-out;
  -o-transition: .25s ease-in-out;
  transition: .25s ease-in-out;
}

#nav-icon3 span:nth-child(1) {
  top: 0px;
}

#nav-icon3 span:nth-child(2),
#nav-icon3 span:nth-child(3) {
  top: 18px;
}

#nav-icon3 span:nth-child(4) {
  top: 36px;
}

#nav-icon3.open span:nth-child(1) {
  top: 18px;
  width: 0%;
  left: 50%;
}

#nav-icon3.open span:nth-child(2) {
  -webkit-transform: rotate(45deg);
  -moz-transform: rotate(45deg);
  -o-transform: rotate(45deg);
  transform: rotate(45deg);
}

#nav-icon3.open span:nth-child(3) {
  -webkit-transform: rotate(-45deg);
  -moz-transform: rotate(-45deg);
  -o-transform: rotate(-45deg);
  transform: rotate(-45deg);
}

#nav-icon3.open span:nth-child(4) {
  top: 18px;
  width: 0%;
  left: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="nav-icon3">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

We will add a click event listener to the third span element, which is where the X is located in this case(I assume).

$(document).ready(function() {
    $('span:nth-child(3)').click(function () {
        alert('X has been clicked') 
    })
});
Related