Enhancing the Syntax of If and If Else in Jquery Functions

I'm struggling to simplify and optimize this block of code. Would appreciate any help in making it more efficient!

var status = "closed";

$(document).on('click', '[data-toggle-nav]', function(event) {


  if ($(this) && status === "closed") {
    console.log('closing');
    $('#top').css('transform', 'rotate(45deg)').css('top', '10px');

    $('#mid').css('transform', 'rotate(-45deg)').css('top', '10px');

    $('#bot').css('display', 'none');
    status = "open";
  } 

  else if ($(this) && status === "open") {
     console.log('opening');
    $('#top').css('transform', 'rotate(0deg)').css('top', '0px');

    $('#mid').css('transform', 'rotate(0deg)').css('top', '10px');

    $('#bot').css('display', 'block');

    status = "closed";
  }

});

Answer №1

To simplify comparisons, it is suggested that the close variable should be a boolean value. Alternatively, achieving the desired outcome can also be done by toggling a CSS class on the necessary elements and manipulating the display state of #bot. Here is an example:

#top {
    top: 0;
}
#top.open { 
    transform: rotate(45deg);
    top: 10px;  
}
#mid.open { 
    transform: rotate(-45deg);
    top: 10px; 
}
$(document).on('click', '[data-toggle-nav]', function(event) {
    $('#top, #mid').toggleClass('open');
    $('#bot').toggle();
});

Example in action

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enhancing User Experience with Google Maps API 3 by Integrating On

I am currently implementing the Google Maps API within a PhoneGap application. Upon clicking on a recognized Google location, an infowindow appears providing details such as website links and URLs. I want to modify the behavior of these default infowindow ...

How to include an href in a button using Pug without disrupting a form

Is there a way to create a button that redirects to my /leaderboard page once my quiz app submits? h1 Play Time 4 Trivia! button Go form(method='POST') ul each val in questions li ...

Convert h264 video to GIF using Node.js

Currently, I'm utilizing the "pi-camera" library to successfully record video in a raw h264 format on my Raspberry Pi. However, I am encountering an issue with the node.js library "gifify" which keeps throwing the error "RangeError: Maximum call stack ...

Tips on avoiding a div from causing its parent's mousemove event to activate if it is concealed

I have a collection of media content with a set of controls positioned above it. I am attempting to implement functionality where the controls will disappear when the user's mouse is inactive and reappear upon mouse movement. However, I am facing an ...

React: The received value for the prop type must be a function, but it was an object

I'm stuck trying to make sense of this error message, and my online search has hit a dead end. Any insights would be greatly appreciated! Attention: Prop type validation failed - expected prop type `leoInfo` to be a function from the `prop-types` pack ...

In NextJS, where is the best place to run sensitive code to ensure it is only executed server-side?

I'm currently exploring the world of NextJS and I am in the process of figuring out how to structure my project with a solid architecture that prioritizes security. However, I find myself at a crossroads when it comes to determining the best place to ...

Prevent additional functions from running when clicking in Angular 5

I have implemented an Angular material table where each row expands when clicked. In the last cell of the table, I load a component dynamically using ComponentFactory. This loaded component is a dropdown menu. The problem arises when the dropdown menu is ...

React Component Functions for Export and Import

Currently working on a webapp built with React. My main component is defined in App.js, while I have another subcomponent responsible for creating buttons, like the logout button generated by renderLogoutButton(). But now, I want to reuse this function in ...

Issue with conditional comment in IE 8 not functioning as expected

Struggling with changing the SRC attribute of my iFrame specifically for users on IE 8 or older. This is the code I have written: <script> var i_am_old_ie = false; <!--[if lte IE 8]> i_am_old_ie = true; <![endif]--> </script> ...

Prevent the div from moving beyond the boundaries of its container while anim

After experimenting with a javascript image panner that I put together from various code snippets, I have decided to switch to a simpler approach. However, I need some guidance on a few things. Below is the code for the left and right buttons: <div id ...

JQuery table sorter is unable to effectively sort tables with date range strings

I am facing an issue with sorting a column in my table that contains text with varying dates. The text format is as follows: Requested Statement 7/1/2014 - 9/16/2014 When using tablesorter, the sorting does not work properly for this column. You can see ...

Guide on verifying Unicode input in JavaScript?

I am looking to create a form where the user can only input Khmer characters (Unicode characters) and display an alert if they input anything else. Khmer Name: <input type="text" class="namekh" name="namekh"> To achieve this, here is a snippet of m ...

Auth0 Angular - No routes found to match

I recently set up an angular application and integrated it with Auth0 by following two helpful tutorials: https://auth0.com/docs/quickstart/spa/angular2/01-login https://auth0.com/docs/quickstart/spa/angular2/02-calling-an-api Here is a brief overview o ...

The JavaScript animations in AngularJS using ng-class are not being activated

I've been attempting to apply js-defined animations to the ng-class directive using the standard syntax of add and remove, but for some reason, the animations are not running. After checking the logs, it seems that the add and remove functions are not ...

Creating a custom script for a search field that retrieves information from an XML document

Attempting to create a script that iterates through an XML file, the provided code currently displays alerts but fails to show information when a valid value is entered into the search field. However, upon removing the error checks and keeping the final ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...

Showcasing the Characteristics of Products in a Table on Prestashop

Dealing with PrestaShop. I have configured attributes for a product and I want to showcase them in a table format similar to this example: The table should display the Paper Size across the top, with each row representing the quantity of paper. In my ad ...

In Laravel, the text-overflow:ellipsis property fails to function properly when trying to display unescaped data

Encountering an issue with the property text-overflow:ellipsis. The ellipsis at the end of the truncated text is not showing up as expected. To maintain formatting without escaping data in ckeditor, I am using: {!! $treatment->description !!} speci ...

The type 'true | CallableFunction' does not have any callable constituents

The error message in full: This expression is not callable. No constituent of type 'true | CallableFunction' is callable Here is the portion of code causing the error: public static base( text, callB: boolean | CallableFunction = false ...

Issues with Bootstrap 5 Carousel Control Button Functionality

My carousel isn't responding when I try to move it by touching the buttons. How can I fix this issue? Code: <div class="container mt-4"> <div id="carouselExampleIndicators" class="carousel slide" data-ri ...