Simultaneous display of icon and text on Bootstrap toggle button

Currently, I am utilizing Bootstrap 3 along with Jquery. Within my coding structure, there is a button that holds an icon within a span tag (specifically using the glyphicon provided by Bootstrap).

<button id="swapArchived" class="btn btn-default btn-sm showArchived">
       <span class="glyphicon glyphicon-road"></span> Show Archived
</button>

The objective is to modify both the icon and text content upon clicking. Are there more efficient methods of achieving this without resorting to repetitive code?

$('#swapArchived').on('click', function () {
    var $el = $(this);
    if($el.hasClass('showArchived'))
    {
      $el.html('<span class="glyphicon glyphicon-fire"></span> Show Incomplete');
    }
    else
    {      
      $el.html('<span class="glyphicon glyphicon-road"></span> Show Archived');
    }
      $el.toggleClass('showArchived');
  });

I am exploring possibilities where the button text and span class can be toggled simultaneously, ideally avoiding excessive manual typing with each click interaction.

Your insights are greatly appreciated -

Answer №1

Give it a shot


jQuery(function ($) {

    $('#toggleView').on('click', function () {
        var $element = $(this),
            textContent = this.lastChild;
        $element.find('span').toggleClass('glyphicon-heart glyphicon-star');
        textContent.nodeValue = 'Switch to ' + ($element.hasClass('showCompleted') ? 'Incomplete' : 'Complete')
        $element.toggleClass('showCompleted');
    });
});

Experience it: Fiddle

Answer №2

To create a dynamic button with changing text and icons, follow these steps:

<button id="toggleButton" class="btn btn-primary btn-sm toggleClass">
    <span class="glyphicon glyphicon-star"></span>
    <span class="text">Toggle Content</span>
</button>

Then use the following jQuery code to handle the button click event and change its attributes:

$('#toggleButton').on('click', function(e) {
    var button = $(this),
        icon = button.find('.glyphicon'),
        label = button.find('.text'),
        toggleClass = 'toggleClass';

    if (button.hasClass(toggleClass)) {
        icon.removeClass('glyphicon-star').addClass('glyphicon-heart');
        label.text('Hide Content');
    } else {
        icon.removeClass('glyphicon-heart').addClass('glyphicon-star');
        label.text('Toggle Content');
    }
    button.toggleClass(toggleClass);
});

Answer №3

To start off, move the text to a different element for easier replacement:

<button id="switchViewed" class="btn btn-default btn-sm changeViewed">
    <span class="glyphicon glyphicon-user"></span>
    <span>Change View</span>
</button>

Next, try implementing something like this:

$('#footer-bottom').click(function(){
    var elem = $(this),
        sibling = elem.next(),
        message  = "Switch Mode";

    if (/Mode/.test(sibling.text()))
        message = "Change View";

    elem.toggleClass("glyphicon-user")
           .toggleClass("glyphicon-heart");
    sibling.text(message);
})

Alternatively, a shorter but less clear option could be:

$('#switchViewed').click(function(){
    $(this).toggleClass("glyphicon-user")
           .toggleClass("glyphicon-heart")
           .next().text("Switch " + 
               /Mode/.test($(this).text()) ? "View" : "Mode");
}

While not overly concise, this solution is fairly decent.

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

Double-data glitch: Jquery inadvertently sending information twice with each click

Hey there, I'm experiencing an issue with my jQuery code where it sends data twice when I click. Can anyone help me figure out why this is happening? $(document).ready(function() { $('#send_message').click(function(e) { e.preventDefa ...

Tips for breaking out of the foundation row and aligning with the right edge of the viewport

I have a CodePen example showcasing the Zurb Foundation grid. I am looking for a way to make a div extend to the right edge of the viewport while keeping the left edge in line with the grid as the viewport is resized. <div class="row"> <div cla ...

Identify which browsers are compatible with HTML5 video autoplay detection

Having completed several projects with video backgrounds that autoplay when the page loads, I have encountered issues with mobile browsers not supporting the autoplay attribute on HTML5 videos. In these cases, an image is loaded instead of the video. To d ...

"Enhance User Experience with the jQuery/JavaScript Table Pagination

I have searched extensively for a jQuery/JavaScript table pagination solution. While I found some options, they were too complex for my needs. I am looking for a simple jQuery plugin to assist with paginating an HTML table. Datatables is more than what I ...

Is it necessary to bring in CSS for the following page?

Should CSS be imported and used across multiple pages in a web application? Is the page structure outlined below considered acceptable, or is there a standard practice to follow? /pages /home index.js index.module.css /cart ...

Adjust the language code in a URL using JavaScript or Node.js

Within my common header file, there is a navbar that includes a multilanguage dropdown menu. The issue I am facing is that when I select a language from the dropdown, the page translates correctly. However, when I navigate to other pages, the selected lang ...

Align the text to the center beneath the image using Jquery's append function

I am looking to showcase a collection of fruits and vegetables through images, with the names displayed centered underneath each image. Additionally, I want to implement jQuery append functionality so that the names only appear when a specific button is cl ...

Which is more effective: coding with just plain JavaScript and CSS, or utilizing frameworks?

As a student, is it more beneficial to focus on utilizing pure JavaScript & CSS or frameworks? And which approach is best suited for the professional field? ...

Ways to adjust the size of the parent element based on the height of a specific element

I am faced with a situation where I need to identify all elements belonging to a specific class and adjust the padding-bottom of their parent div based on the height of the matched element. For example, consider the following structure: <div class=&ap ...

Passing references between multiple components

I'm currently working on an application using Material-UI in conjunction with styled-components. I am faced with the challenge of passing a ref down to the root <button> node that is created by Material-UI. Material-UI provides a buttonRef prop ...

I am currently attempting to create a JavaScript function that searches for the <td> elements within an HTML table. However, the function fails to work properly when there are <th></th> tags included

UPDATE: Scratch that, I managed to solve my issue by creating a separate table for the header to contain all of my <th> tags I am working with an HTML table and I would like to add a search bar to filter through the content since it is quite large. ...

My navigation bar is giving me a bit of trouble, as there are two separate issues that seem to be interconnected

Looking for some help with my navigation bar layout. You can also check out the code on fiddle http://jsfiddle.net/SgtRx/ (should have done this earlier, sorry). I'm a beginner when it comes to coding, so please bear with me if I make any mistakes. ...

What is the purpose of the tabindex in the MUI Modal component?

Struggling with integrating a modal into my project - it's refusing to close and taking up the entire screen height. On inspection, I found this troublesome code: [tabindex]: outline: none; height: 100% How can I remove height: 100% from the ...

Enigmatic void appears above row upon removal of content from a single item

When I click on an item in my grid, the content of that item is moved to a modal. The modal functions properly, but I noticed that when the content is removed from the item, a space appears above it. I have found that using flexbox could solve this issue, ...

Increase a variable within a looping structure using jQuery

I am faced with a task that involves selecting two values from different dropdown lists, such as 1001 from the first dropdown and 1003 from the second. Upon clicking the 'add' button, I need to pass these selected values, along with the values in ...

When sorting items, the page automatically jumps to the top of the screen

I have been working on creating a sortable portfolio using jQuery. One issue I am facing is that every time I click on a filter for the portfolio items, the page automatically scrolls to the top. Is there a way to prevent this from happening? You can vi ...

The excessive load time of my ajax request within a for loop is causing delays when calling a php file

My Ajax request is taking a long time to load as I'm calling the ajax function from 1 to 3000. It queries the database for each value and returns if the value exists in the database. function GetData(id) { id = id; jQuery.ajax({ type: "GET", ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Performing an AJAX call in Rails 4 to update a particular value

I have a voting button on my website that displays the number of votes and adds an extra vote when clicked. I want to implement Ajax so that the page doesn't need to refresh every time a user votes. However, I am new to using Ajax with Rails and not s ...

Is there a way to ensure that the elements created by the select form are only generated once?

I have a JavaScript function that dynamically creates paragraph and input elements based on user selection in HTML. However, I am looking to optimize the code so that each element is only created once. Snippet of JavaScript code: function comFunction(sel ...