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

Navigational menu that slides or follows as you scroll

Wondering if anyone knows of a straightforward jQuery or Javascript method to create a navigation sidebar that smoothly moves with the user as they scroll down a page. A good example can be found here: Any suggestions would be greatly welcome. ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Tips for enhancing the appearance of a React component

I have a redux form that doesn't look great, and I would like to style it. However, my project uses modular CSS loaders. The styling currently looks like this: import styled from 'styled-components'; const Input = styled.input` color: #4 ...

The module specifier "tslib" could not be resolved due to a TypeError. It is necessary for relative references to begin with either "/", "./", or "../"

Hey there, I recently started learning npm. I'm trying to install "@fullcalendar" and use it, but I keep getting this error message: "Uncaught TypeError: Failed to resolve module specifier "tslib". Relative references must start with either "/", "./", ...

What is the most effective way to receive all values sent to an Observer upon a new subscription?

I have an observer that receives various values emitted to it at different times. For instance sub = new Subject<any>(); sub.next(1); sub.next(2); sub.next(3); #hack 1 sub.next(4); sub.next(5); sub.next(6); #hack 2 If there is a ...

Execute the dynamic key API function

Below is the data object: registration: { step1: { project: '', }, step2: { adres: '', facade: '', floor: '', }, }, An attempt is being ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

Retrieving a tag from bs4.element.tag results in an empty value

As I follow a tutorial to extract answers from a Quora URL, my code is set up like this url = 'https://www.quora.com/Should-I-move-to-London' r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') answers = soup.find(" ...

Troubleshooting AJAX, PHP, and mySQL Interactions

I am experiencing issues with my password change script on my website. I am utilizing an AJAX connection to my php file. While my database connection seems stable and variables are being sent correctly (based on firebug), they seem to disappear along the w ...

After using promise.all, I successfully obtained an array of links. Now, how do I calculate the total number of links in the array?

function verifyAndTallyURLs(linksArray) { let validations = linksArray.map((link) =>{ return fetch(link) .then((response) => { return { webpageURL: response.url, status: response.status, ...

show the stored value inside the useRef variable

One of my challenges involves a variable const prediction = useRef<any>(null); A button triggers a function that updates the variable's value: function showResult() { classifier.current.classify(capture, (result) => { ...

Steps to create an automatic submission feature using a combobox in HTML5 and then sending the retrieved data back to the HTML file

Here is the code snippet I've been working on: <strong>Station Name</strong> <!--This portion includes a combobox using HTML5 --> <input type=text list=Stations> <datalist id=Stations> <option>Station1</opt ...

issue with a non-functional sticky sidebar within a Tailwind post

I am trying to create a layout similar to this website. One of the key features I want to replicate is the sidebar that follows you as you scroll. Here is the code I have, but unfortunately, I can't seem to get it to work: <template> <di ...

A guide to setting an href using variable values in jQuery through manual methods

I have a datepicker set up where each day, month, and year is stored in a variable. I then display this information in the desired format. Below is the jQuery code: jQuery(document).ready( function($){ alert('alert function'); var txtFr ...

Looking to screen usernames that allow for the use of the DOT (.), underscore (_), and Dash (-)?

I am using jQuery to filter usernames that are exactly 3 characters long. The validation criteria includes only allowing the following special characters: ., _, and - var filter = /^[a-zA-Z0-9]+$/; Therefore: if (filter.test(currentval)) { //valid ...

Is there an issue with Vue-router 2 where it changes the route but fails to update the view

I am currently facing an issue with the login functionality on a website that utilizes: Vue.js v2.0.3 vue-router v2.0.1 vuex v0.8.2 In routes.js, there is a basic interceptor setup router.beforeEach((to, from, next) => { if (to.matched.some(record ...

Utilize time in submitting a form

Is it possible to schedule a form submission at a specific time, such as 12:00? I have already created a countdown timer and now would like the form to be submitted automatically at a certain time. <html> <head> </head> <body> ...

What is the best way to add a value to the value attribute of a div using JavaScript?

Is there a way to insert a value into the value attribute of a div using Internet Explorer 9? I have attempted various JavaScript functions, but so far I can only modify the content inside the div and not the value attribute itself. <div id="mydiv" val ...

Having difficulty adjusting the width of a div element

I've been struggling to adjust the width of the div assigned with the colors class, whether in percentage or pixels. var colors = ["RED", "GREEN", "BLUE", "YELLOW", "PURPLE"]; for (var h = 0; h <= 4; h++) { for (var i = 0; i <= colors.lengt ...

tips for accessing variables within app.get

Is there a way to make a variable or a set of variables inside app.get accessible throughout the entire project? I am working on capturing information from an SMS text message, organizing it into the "messageData" variable, and then sending it to the "Mess ...