Steps to switch the displayed ionicon when the menu is toggled

My goal is to display the 'menu-outline' ionicon on my website until it is clicked, at which point the icon will change to 'close-outline' and vice versa. I am utilizing jQuery for this functionality.

Although I am aware of how to toggle classes, my ionicons are identified by their names rather than classes:

<a class="menu-button js-menu-button"><ion-icon name="menu-outline"></ion-icon></a>

Currently, my jQuery code toggles the menu but doesn't handle the icon switching:

 $(".js-menu-button").click(function() {
    var nav = $(".js-main-nav");
    var icon = $(".js-menu-button ion-icon");
    /* appear and disappear */
    nav.slideToggle(200);
});

I am wondering if there is a way to toggle the name of the icon or if there is an alternative approach to achieve this effect. Any suggestions would be greatly appreciated. Thank you.

Answer №1

If you want to switch the icon name, you can use the following code snippet:

$(".js-menu-button").click(function() {
    var nav = $(".js-main-nav");
    var icon = $(".js-menu-button ion-icon");
  
    if (icon.attr("name") == "menu-outline") {
      icon.attr("name", "close-outline");
    } else {
      icon.attr("name", "menu-outline");
    }
  
    // Toggle visibility
    nav.slideToggle(200);
});

Alternatively, you can achieve the same result with this code:

$(".js-menu-button").click(function() {
    var nav = $(".js-main-nav");
    var icon = $(".js-menu-button ion-icon");
    
    icon.attr('name', function(index, attribute) {
        return attribute == "menu-outline" ? "close-outline" : "menu-outline";
    });
    
    // Toggle visibility
    nav.slideToggle(200);
});

Answer №2

It could be past the typical hours, but I encountered a similar issue while working in JavaScript. A practical solution would be to define a class (such as 'toggle-mode') within your ion-icon element like so:

<ion-icon class="toggle-mode" name="moon-outline"> </ion-icon>

Once you have done this, you can easily access and modify the icon name (using toggle-mode.name) with an approach like the one shown below:

toggleMode.name =
    toggleMode.name == "moon-outline" ? "sunny-outline" : "moon-outline";

In this scenario, I am switching between 'sunny-outline' and 'moon-outline'.

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

Tips for showing an image during an asynchronous postback

I've implemented an Ajaxable application with UpdateProgress for each postBack event, and it's all working perfectly. Now, I'm looking to add another Indicator in my SiteMapPath bar to show that a postback is taking place at any given time. ...

After examining the width properties in the CSS code, it was discovered that one particular icon is larger in

Is there a way to adjust the width of the first icon in my container using CSS? The first icon appears larger than the others, and I'm having trouble making it the right size. #features { margin-top: 35px; } .grid { display: flex; } #feat ...

IE7, IE6 display margins differently compared to other browsers

Can anyone help with an issue I'm having with a CSS ul list menu? #header-container #header ul.top-nav { float: left; margin: 20px 0 20px 10px; } #header-container #header ul.top-nav li { float: left; margin-right: 8px; border-rig ...

What is the best way to conduct a conditional check across all subsequent visible rows of a table?

When a user clicks inside the text input field and presses either the down or up arrow keys, my JavaScript function is triggered. The purpose of this functionality is to search table values and allow the user to select one by pressing the arrow keys. Every ...

How can I align bullets in an unordered list with the left margin of the heading above?

Is there a way to line up the bullets with the left margin of the text above the list? Here's an example: <html> <style> ul.p1 {padding-left: 40px} ul.p2 {padding-left: 0px} </style> <body> <h2&g ...

What is the reason for receiving a JSX warning even though JSX is not being utilized in the code?

In my Vue.js component file using the Quasar framework, I have the following code block inside the <template>: <q-btn color="green" label="save & continue editing" @click="saveCase()" /> This snippet is par ...

The initial JSON array is displaying correctly, however the subsequent nested arrays are appearing as [Object, object]

I am currently utilizing a wordnik API to gather the word of the day and extract array information. However, I am encountering an issue where the nested arrays are displaying as "object, object" rather than the expected data <script src="https://ajax ...

Tips for creating an HTML page with the dimensions of an A4 paper sheet?

My goal is to display the HTML page in a browser while containing the content within the dimensions of an A4 size page. Additionally, when printed, the HTML page should be formatted to fit onto A4-sized paper pages. <div classNa ...

ReactJS component state fails to update accurately

Let's say I have a component named Test import {useEffect, useState} from "react"; const Test = (props) => { const [Amount, setAmount] = useState(1); useEffect(()=>{ if(props.defaultAmount){ setAmount(prop ...

A loop in JavaScript/TypeScript that runs precisely once every minute

Here is a snippet of my code: async run(minutesToRun: number): Promise<void> { await authenticate(); await this.stock.fillArray(); await subscribeToInstrument(this, this.orderBookId); await subscribeToOrderbook(this, this.orderBookId ...

Why is my index.tsx file not properly exporting? (React + Typescript)

I've developed a basic Context Provider that I'd like to package and distribute via npm. To package my code, I utilized the create-react-library tool. In my project, I've set up an index.tsx file that should serve as the entry point for im ...

Assistance with Jquery for toggling checkboxes when labels are clicked

I'm currently working on a feature that allows for checking and unchecking checkboxes upon label click. You can find my Jsfiddle here: http://jsfiddle.net/PTAFG/1/ The HTML structure cannot be altered Here is the snippet of my HTML: <div style= ...

Warning happens two times upon performing a right-click

I've got some code that checks the mouse's position, and triggers an alert followed by a redirect if a certain condition is met. It functions correctly, however, I noticed that if you right-click in one area and then left-click in another area t ...

Tips on validating individual array elements in Laravel

I'm working with an array of indexes that stores data retrieved through an AJAX call. My goal is to implement validation on only one specific index within the array. Here is the relevant section of my code: foreach($request->info as $info){ ...

What is the best way to conceal a set of columns and reveal them upon clicking a header column?

Currently working with Bootstrap 3 and successfully split the top into two columns. I am aiming to replicate the design shown in the sample image without relying on JavaScript or jQuery. Upon clicking "Quick Info", there should be a new set of columns reve ...

Refresh table in php without the need to reload the entire page

Currently, I am retrieving data in a table from the database and have three buttons - update, delete, and an active/inactive button. Each button has its own functionality, but I need to reload the updated data in the table after any event without refreshin ...

The positioning of jQuery UI elements seems to be off

I'm having an issue with the positioning of a dropdown box under its button using the jQuery UI position function. The dropdown box is not aligning correctly. Check out the fiddle for reference. $(".dropDown .dialogueBox").position({ my: " ...

The issue with the ng-click property not triggering arises when it is assigned to a button that is generated dynamically

I need to construct a table dynamically based on the results returned from SQL. In this scenario, populating the table with the start time, end time, and user is straightforward: var StartTime = document.createElement('td'); var EndTime = docume ...

Protractor: Locating Elements Based on Attributes

I have been looking for a specific element to test: <div class="alert alert-danger" role="alert" ng-show="notValid">Zugangsdaten eingeben</div> How do I locate this element to verify its visibility based on the ng-show attribute? The ng-show ...

What is the syntax for using escape characters in Vue?

Looking to create a website similar to CodePen? I have developed a library of assets including buttons, cards, and effects, all built using vue.js. Each asset includes HTML, CSS, and sometimes JS code. In my vanilla JS version, I formatted the code using e ...