I'm experiencing difficulty getting my code to function properly when adding or removing classes with Bootstrap Glyphicons

Recently, I decided to play around with bootstrap's glyphicons. By utilizing Jquery's addClass and removeClass functions, I tried to smoothly transition from one glyphicon to another.

Here is the code snippet:

var glyphOn = true; //The glyphOn variable keeps track of whether .navList is visible or not.

$('.glyphicon').click(function() {
  if (glyphOn == true) {
    $('.navList').fadeIn(500).addClass('glyphicon-remove').removeClass('glyphicon-align-justify');

    glyphOn = false;
  } else {
    $('.navList').fadeOut(500);
    glyphOn = true;
  }
});
/*This CSS is mainly for demonstration purposes and can be disregarded. The key point here is that .navList has display:none;*/

.glyphicon {
  background-color: gray;
  padding: 15px;
  font-size: 2em;
  color: white;
  cursor: pointer;
}
.navList {
  display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!--A sample example using two commonly used glyphicons in Mobile Web Development.-->
<p><span class="glyphicon glyphicon-align-justify"><!--As per bootstrap documentation, the content inside this tag should be empty.--></span>
</p>
<ul class="navList">
  <li>List Item 1</li>
  <li>List Item 2</li>
  <li>List Item 3</li>
</ul>

I apologize if this seems like a simple issue, but despite my efforts to find a solution online, I haven't been successful.

To clarify, let me state the objective and challenge:

GOAL: To effectively swap glyphicons within an element. (Specifically, switching between a Mobile Menu Glyph and an Exit Glyph.)

PROBLEM: The provided code snippet doesn't perform as intended.

Thank you in advance to anyone who provides insights and solutions :)

Answer №1

let isGlyphOn = true; // This boolean variable keeps track of whether .navList is visible or not.

$('.glyphicon').click(function() {
  if (isGlyphOn) {
    $('.navList').fadeIn(500);
    $(this).addClass('glyphicon-remove').removeClass('glyphicon-align-justify');

    isGlyphOn = false;
  } else {
    $('.navList').fadeOut(500);
    $(this).removeClass('glyphicon-remove').addClass('glyphicon-align-justify');
    isGlyphOn = true;
  }
});

A highlighted issue, as pointed out by Khalid in the comments, is that you're changing the class of the ul element instead of the glyphicon element (referenced as "this" since it triggers the function).

To improve the code, I suggest using event listeners on the glyphicon element's class to achieve the same outcome, or even better, toggle between "remove" and "align-justify" classes as demonstrated below.

$('.glyphicon').click(function() {
  $('.navList').fadeToggle(500);
  $(this).toggleClass('glyphicon-remove').toggleClass('glyphicon-align-justify');
});

Answer №2

To make it work, all you need to do is replace glyphicon-remove with glyphicon

$('.glyphicon').click(function () {
     if (glyphOn == true) {
        $('.navList').fadeIn(500).addClass('glyphicon').removeClass('glyphicon-align-justify');

        glyphOn = false;
     }else{
        $('.navList').fadeOut(500);
        glyphOn = true;
     }
});

Answer №3

Here is a code snippet for you to try:

I have assigned the mnIcon class to a span element and in JavaScript, I have used addClass and removeClass for the span, not ul navList.

var glyphOn = true;
$('.glyphicon').click(function () {
if (glyphOn == true) {
$('.navList').fadeIn(500);
$('.mnIcon').removeClass('glyphicon-align-justify');
$('.mnIcon').addClass('glyphicon-remove'); 
glyphOn = false;
} else {
$('.navList').fadeOut(500);
$('.mnIcon').removeClass('glyphicon-remove'); 
$('.mnIcon').addClass('glyphicon-align-justify');
glyphOn = true;
}
});
.glyphicon {
background-color: gray;
padding: 15px;
font-size: 2em;
color: white;
cursor: pointer;
}

.navList {
display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p><span class="mnIcon glyphicon glyphicon-align-justify"></span></p>
<ul class="navList">
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
</ul>

Answer №4

To make the menu clickable, remember to apply the class to the clicked menu item rather than the entire list. Check out the following code snippet for a working example:

$('.glyphicon').click(function() {
      if (glyphOn == true) {
        $('.navList').fadeIn(500);
$(this).addClass('glyphicon-remove').removeClass('glyphicon-align-justify');

        glyphOn = false;
      } else {
        $('.navList').fadeOut(500);
$(this).addClass('glyphicon-align-justify').removeClass('glyphicon-remove');
        glyphOn = true;
      }
    });

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

Querying Mongoose Nested Data in Express: A Comprehensive Guide

I need to retrieve the "stocked" boolean value for item "4" belonging to user "456" from my mongoose data collection. However, when I try to query for this specific information, I end up receiving the entire user object instead. Data: data = [{ use ...

Extra Pathway

Having trouble adding a second route to the /privacy page. The error "Cannot GET /privacy.html" keeps popping up. Any suggestions? This code seems to be failing to display the privacy.html content app.get('/privacy', function(req, res) { res.s ...

Stop mega menu items from disappearing when hovered over

I'm currently working on a web page that features a mega menu. When I hover over the mega menu, it displays its items. However, when I try to hover over the items, they disappear. Here is the HTML code snippet: <li class="dropdown mega-dropdown m ...

Ways to display a price near a whole number without using decimal points

Currently, I am working on an ecommerce project where the regular price of an item is $549. With a discount of 12.96% applied, the sale price comes down to $477.8496. However, I want the sale price to be displayed as either $477 or $478 for simplicity. Yo ...

What is the best method for converting a variable with HTML content into a printable string?

In an attempt to display user-entered data from a text box to an HTML div, there seems to be an issue when the data contains HTML content. Instead of displaying the content as a string, it shows it as HTML elements. For example: let text = "<h1>Worl ...

Assessing the value of a variable or expression embedded within a string in Sass

Creating a mixin to set a div to transparent requires special attention to evaluate a variable in a string. The -ms-filter line must be quoted and should include the result of a calculation ($amount * 100). How can I successfully incorporate this into my ...

Ways to connect css file to ejs views in nodejs

Currently, I am tackling a beginner node.js server project. While I have successfully managed to render dynamic HTML using ejs templates, I seem to be facing difficulties when it comes to linking CSS styling to these templates. In an effort to address thi ...

I'm experiencing a flickering issue with my carousel when it reaches over 10,000 pixels during animation. Could this be related to a jQuery problem

After my carousel moves past 10000 pixels, it starts flickering through multiple elements. I'm utilizing jCarousel Lite: Could this be a jQuery-related issue? My initial assumption is that it may be specific to jCarousel Lite, but there doesn't ...

The V-model is failing to bind properly as anticipated

One feature of my application involves a table that displays a list of products. Each product row in the table has an input field where users can enter the quantity they want to purchase. The total cost for each product is dynamically calculated by multipl ...

When the IF condition in HTML is used in conjunction with Java code, it is causing all HTML code to be ignored and

Everything works perfectly if "sh" has a value (such as "Day" or "Night"), but when it is empty or null, it triggers a null condition and skips all the code on my HTML page, leading the control to the end of the HTML file. Question: I have tried using els ...

Using Placeholder Attribute in HTML5 Inside Struts HTML:text Tag

In the web application I am developing with Struts 1.3.10, I would like to add placeholders to my textfields. However, the current Struts taglib does not support this feature and I prefer not to rely on JavaScript for implementation. Are you aware of any ...

AngularJS - $scope.$destroy does not eliminate listeners

I am currently exploring how to develop my own "one-time binding" functionality for AngularJS version 1.2 and earlier. I came across this response which explains the process of creating a custom bindOnce directive. Upon using the provided directive: a ...

Storing JSON location data in JavaScript

When converting JSON data into a list structure, I aim to use the "AAA.BBB[0].CCC.DDD[5].EEE" format as the ID. This way, any modifications made by a user to the content of that specific list item will directly affect the JSON data linked to that location. ...

How can I declaratively bind the properties in Dojo's _hasDropDown method?

UniqueSearchComponent.html: <div class="${baseClass}"> <div data-dojo-type="dijit/_HasDropDown" data-dojo-props="dropDown: 'containerNode'"> <div data-dojo-type="dijit/form/TextBox" name="${SearchViewFieldName} ...

jQuery: a handy DIY infinite scroll technique that's super easy to implement

While there are countless plugins available, I am curious about how I can customize my own solution to work exactly as I envision. My goal is to automatically trigger a function called ajaxLoadActivity when the user scrolls to the bottom of the page, inst ...

Footer content spilling out of the wrapper div

My web page has a footer content that is overlapping the wrapper div due to some issues with my css and html. Even when I tried changing the height to auto, it didn't resolve the problem. Below is an example of the current state of the page I am worki ...

Discover how to utilize Firebug in Java to access a node's CSS properties

Is there a way to access all properties (CSS, etc) of web page nodes using Firebug within Java code without relying on XPath? I would like to retrieve all available properties instead of checking for them individually. Any advice on how to achieve this? ...

Arranging an array of objects based on a specific keyword and its corresponding value

I have an array of objects that looks like this: [ { "type": "Exam", "value": 27 }, { "type": "Lesson", "value": 17 }, { "type": "Lesson", &qu ...

Retrieve all attributes of an element with the help of jQuery

I am attempting to extract all the attributes of an element and display their names and values. For instance, an img tag may have multiple unknown attributes that I need to access. My initial idea is as follows: $(this).attr().each(function(index, element ...

Image transformation not rotating the image

I'm having trouble making an image of an X rotate 180 degrees when it's hovered over. Instead of rotating, the image just moves up and to the right. What am I missing that's preventing this from looking like a smooth 180-degree spin? .bl ...