What is the method to change the state of Bootstrap 4 buttons in a mobile view without using CSS classes as a reference?

I have a simple example featuring a few buttons displayed in a basic modular popup. I am curious about how the state changes from active to inactive as I don't see any visible change in my code.

Initially, I attempted to use custom JS to add an "active" class on click and remove it on the second click, but at least one button (the most recently clicked) stayed selected even without the "active" class being attached to it.

I have provided a code example on Codepen.io here, where those buttons behave differently compared to what is expected by default, right?

Please advise me on what I might be overlooking.

<button type="button" class="btn btn-outline-secondary w-100">1</button>

Update:

The default behavior of the buttons varies depending on whether in Desktop or Mobile view. You can test this on the Codepen example - in mobile view, the last clicked button remains "selected/dark" (with a color change and focus around it), while in desktop view, it instantly reverts back to white when the mouse moves away.

I am currently working on selecting multiple buttons by adding an active state - however, handling this mobile behavior poses a challenge because at least one button appears selected even without the "active" class being applied to it.

My question is, how can I make such a button appear normal again (like the unselected ones) programmatically?

In other words, while selecting multiple buttons doesn't seem to be an issue, I want to allow users to deselect buttons if they make a mistake, which is where the complication arises. Here is another link to the Codepen with the same example and some added JS functionality to add/remove the active class from buttons - try it out in mobile view here, attempt to select a few numbers and then deselect one or two.

Screenshot update upon request - in mobile view, button six may appear selected, but it was actually deselected and the .active class has been removed from it.

https://i.sstatic.net/UsBlv.png

Answer №1

To begin with, there is no need to manually code JavaScript in order to toggle the .active class on buttons. Bootstrap provides a convenient button plugin that can be utilized:

<button type="button" class="btn btn-outline-secondary w-100" 
        data-toggle="button" aria-pressed="false">1</button>

This will automatically handle toggling the .active class when the button is selected or deselected.

Check out this demo on jsfiddle: https://jsfiddle.net/davidliang2008/mfqyp8j3/6/


Furthermore, selecting a button triggers two actions. When using the Bootstrap button plugin, the .active and .focus classes are added:

https://i.sstatic.net/41qWi.png

  • .active: applies the same background color as when hovering over the button
  • .focus: adds a shadow effect around the button

Upon clicking elsewhere, only the .focus class is removed. This results in the button retaining its filled background color without shadows, akin to hovering over it.

If you unselect a button while still pointing at it, the .active class is removed but the hover and focus effects persist, giving the appearance of the button being selected. Only moving your mouse away from the button eliminates the hover effect, leaving just the focus shadow.


If you wish to enhance the visual distinction between selecting and deselecting a button, you can customize CSS to disable the hover effect specifically when the button has the .focus class but not .active:

.selector .btn.focus:not(.active):hover {
    color: inherit;
    background-color: inherit;
    border-color: inherit;
}

Take a look at the demo on jsfiddle: https://jsfiddle.net/davidliang2008/mfqyp8j3/17/

Also available as a Codepen demo: https://codepen.io/davidliang2008/full/yLJRZYy


Here's a gif demonstrating proper functionality in mobile view: https://i.sstatic.net/iawoO.gif

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

`Looking for a solution: Bootstrap failing to align right properly`

In my Bootstrap 4 project, I am facing an issue with aligning a label and an icon within a Card-Header. I want the Label to be left-aligned and the icon to be right-aligned, but for some reason, the icon is always attached to the label instead. Even when I ...

What is the best way to reduce a varying percentage as the value continues to rise?

My memory of math may be a bit fuzzy, but I can't seem to recall how to solve this particular issue. In jQuery, I have been adding randomized clipping paths to my images using the following code: var max=100; var spread=5; jQuery.each( $("img"), func ...

Instructions on converting Dart to JavaScript for a non-web platform

I am interested in compiling Dart to JS for a non-web target, such as fermyon/js or node How can I compile Dart to JS for a non-web target? Update: I have been informed that it is possible, and although I couldn't find specific documentation, there ...

Steps for making a Trello card via a Discord bot

As a beginner in Java script coding, I am attempting to create a bot for adding a card to my Trello board. Despite hours of searching online, I have not been able to find a solution. if(isCommand('gameban', message)){ if(!message.membe ...

What is the most effective way to retrieve the full height of a webpage using JavaScript

  Is there a way to get the actual height of the webpage, not just the browser screen height? I noticed that clientHeight only returns the height of the window! Thank you for your help! ...

Clicking on the image in an owl carousel slider does not trigger the onsen template page to load

I am experiencing an issue with my owl carousel slider while calling an API for page content on image click. I have implemented an onsen template page using ng-click on image, but it only works for the first image click. Subsequent images do not call the o ...

Using Javascript to multiply strings

While working on the leetcode problem related to multiplication, I encountered an interesting issue. Given two non-negative integers num1 and num2 represented as strings, the task is to return the product of these two numbers, also in string form. However ...

Navigating through JSON arrays with Node.js

I have been given the task of iterating through a complex JSON file that contains an array of JSON objects. I am finding it difficult to access the array object within the JSON file. Specifically, I need to access the "class-name" object from the JSON f ...

Unable to display MathJax content on the HTML webpage

After implementing MathJax in the header of the page: <script type="text/javascript" id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> I inserted Latex into the ...

Customizing Thickness for Tab Labels in MUI 5

I have been trying to adjust the thickness of the label inside a tab using MUI 5, but so far I haven't had success. Here is what I have attempted: interface TabPanelProps { children?: React.ReactNode; index: number; value: number; } funct ...

Sort columns in a MUI datatable

I am facing an issue with sorting in a column that represents an object. Although I can display the desired value, the sorting functionality does not seem to work for that particular column. Here is an example to provide better clarity: const [data, set ...

Modifying the color scheme of Bootstrap

In order to simplify referencing, I am establishing new theme colors as shown below, allowing me to use classes like bg-red instead of bg-danger or text-purple, and so forth. $primary : #24305e; $blue : #375abb; $indigo : #796eff; ...

Guide to importing multiple controllers using express

For my upcoming full stack project, I am working on various controllers like signup, login, and profile. Instead of manually requiring each controller and adding them to the app using individual lines of code, I am seeking a more efficient solution. I env ...

Creating dynamic buttons and textboxes on a JSP page

<form:form action="approveAccount.html" method="GET"> <input type="submit" value="approvAll"/> <p>List of Pending Accounts for Approval</p> <c:forEach items="${accountIdList}" var="val"> <li>${val}</li> ...

Tips for properly positioning the ko validation message in case it is lengthy

I have implemented ko validation messages in order to validate input fields. Can anyone provide guidance on how to align the validation message correctly within the specified location? <input id="personName" class="form-control placeholder has-error" t ...

Retrieve the hidden value buried within multiple layers of classes

I'm having trouble retrieving the value from the pickup-address class. Here is my current code. Can anyone help me identify where I might be going wrong? JS var pickupAddress = $('.timeline-item.active-item > .timeline-status > .pickup-add ...

-=:Heading with a decorative vertical line=:-

Currently, I am working on a CSS project that requires page titles (headings) to be centered with horizontal lines positioned vertically on both sides. Additionally, there is a background image on the page which means the title's background must be tr ...

Need Some Help Reversing the Direction of This CSS Mount Animation?

Exploring this fiddle, I encountered a small div showcasing an opacity animation. The animation smoothly executes when the state transitions to true upon mounting the component, causing the div to fade in beautifully. However, I faced a challenge as the an ...

Ways to determine the success of $wpdb->query and retrieve the outcome

Currently, I am in the process of developing a WordPress website, I have implemented a form that allows users to make modifications and update the database: Below is the HTML/PHP code snippet: echo '<form class="form-verifdoc" target=&q ...

When the user initiates a fetch request, they will be directed to the POST page as a standard

Whenever I utilize fetch for a post request, I encounter an issue where the user is not redirected to the Post page as they would be with a regular form submission. My goal is to be able to direct the user to a specific location on the server side at app ...