Is it feasible to maintain the color of an element after clicking a button with the use of arrays?

Is it possible to make a button retain its hover color even after it has been clicked using a php/ejs script? The script is running on Ajax, so the page does not refresh.

I have managed to get the color retention feature to work, but it always defaults to the blank (0) / 'amount' class regardless of which button I click on.

I also attempted to hardcode IDs to differentiate the classes, but unfortunately, that did not yield any success.

Here is the current code snippet from the template file/ejs:

<% _.each(model.information_amounts, function(info) { %>
        <div class="classBlock"> 
                <button type="button" name="info" value="<%= info.amount ? info.amount : '' %>" id="info" class="amount"><%= info.name %></button>
        </div>
<% }) %>

This code snippet loops through an array and displays all the button options available.

Attempts made:

<% _.each(model.information_amounts, function(info) { %>            
      <div class="classBlock"> 
                <button type="button" name="info" value="<%= info.amount ? info.amount : '' %>" id="info" class="amount<%= info.id %>"><%= info.name %></button>            
      </div> 
<% }) %>

[I also hardcoded the stylesheet class for amount1 and similar ones.]

Current Stylesheet:

 .amount {
     background-color:#c0c0c0;
}
.amount:hover, .amount:focus,.chosen {
     background-color:#000;
}

Another approach tried with Ajax in common.js:

$('#info').on('click',function(){
    $(this).toggleClass('chosen');
});

It is uncertain if this is relevant to the question, but here's the js event:

    events: {
        'click button#info': 'updateInfo',
},

Update: Experimented with the solution provided above, however, it did not produce the desired outcome. Considering that the template is enclosed within EJS, is there anything specific that needs to be done to ensure this functionality works as intended? It seems rather perplexing why simple js rollovers and color changes are not working in this scenario.

Stylesheet:

  .amount1 {
     background-color:#c0c0c0;
  }
  .chosen1, .amount1:hover {
       background-color:#000;
  }

common.js Yes, this file is indeed being called from the page. There are no errors reported in the console:

 $('.amount').on('click',function(){
    $(this).toggleClass('.chosen1');
});

Button input from the EJS template:

<button type="button" name="info" value="<%= info.amount ? info.amount : '' %>" id="info" class="amount<%= info.id %>"><%= info.name %></button>

Answer №1

If you're searching for the pseudo-class :visited, include it in your CSS as a selector and make sure to use the same color you applied for :hover.

Visit MDN

Answer №2

Here is a summary of what unfolded: - The element underwent a refresh. - I needed to manipulate the session in PHP to send a 'true' variable back to EJS, ensuring the correct button maintained its color.

For those curious, here are the steps I took: - Added a session variable in PHP to store the button value:

$this->session->data['selectedamount'] = $this->session->data['amount'];

In EJS:

<% 
    if(model.successes.selectedamount !== info.amount){ 
        var chosenclass ='amount';
    }else{
        var chosenclass ='chosen';
    } 
%>
<button type="button" name="info" value="<%= info.amount ? info.amount : '' %>" id="info" class="<%= chosenclass %>"></button>

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

How to convert table headings in Bootstrap-Vue.js

For a few nights now, I've been struggling to translate the table header in my vue.js component. It seems like I'm missing something as I'm new to Vue.js and can't seem to figure out what's wrong. Translating within the HTML works ...

Creating a Vibrant Progress Bar with Multiple Colors: A Step-by-Step Guide

I'm still getting the hang of things, so I apologize if my question isn't perfectly clear. What I'm trying to do is create a dynamic progress bar with multiple colors that animates upon loading the page. I've seen some examples similar ...

How can I load a function from the HTML file that is being loaded using .load() in jQuery?

Within my main window main.html, there is a div button that, when clicked, loads another html file into a large div. This is achieved using the .load() function: $('#mainpanel').load("search.htm"); The "search.htm" file contains a function cal ...

Welcome to the Kickme command in Discord.js!

I am attempting to create a command that enables any user to trigger the !kickme command, which will result in them being kicked from the server. Additionally, I want the command to send a direct message to the user who initiated it. However, I am facing ...

Javascript code successfully executed using ajax

Using ajax, I have successfully implemented the 'addScript' function to add a js file to the loaded page. The following code snippet works perfectly: addScript('SlimBox/js/mootools.js'); However, I am encountering an issue when trying ...

How can the CSS percentage be converted to pixels for the bottom parameter?

Within my CSS file, I have the following code snippet: #myClass { position: absolute; height: 6px; width: 100%; bottom: 66%; << here is 66% left: 0; right: 0; background-color: #666; cursor: n-resize; } Currently, ...

Determining the rotation direction following an object collision using three.js

In my three.js demo, collision detection is achieved using a Raycaster that extends from the front of the camera. The movement of the camera is restricted to follow its facing direction, although the mouse controls allow for steering in different direction ...

The creation of a SharePoint item through Kendo UI Scheduler is unsuccessful due to the absence of a

While using the Kendo Scheduler with a SharePoint list, I encountered an issue when trying to add/create a new item. Editing and displaying items works fine, but upon saving a new item, I receive a bad request error without any JavaScript errors. The probl ...

Is there a way to display the next/previous buttons separately from the scroller in my jQuery thumbnail scroller implementation?

Is there a method to display the next and previous buttons outside of the scroller frame when using jQuery thumbnail scroller by manos.malihu.gr? I have attempted to modify the button class in CSS to make them more prominent or visible, but unfortunately ...

response from jquery when condition is met

Currently, I am utilizing jquery-ajax to transmit data to a PHP file. Once the transmission is complete, the PHP responds back. In this case, everything is running smoothly. However, I'm faced with uncertainty regarding how to implement an if statemen ...

Adjust the JQuery UI Slider value in real-time as you slide the slider

I am currently using a jQuery slider. When I slide the slider, I test for a specific scenario in the slide function. If the scenario is not met, the slider should revert back to its original position. For instance: Let's say the current slider value ...

Every time I use Get for ajax calls, I keep getting hit with a frustrating

Initially, I was making a call to a [web method] using the POST method. However, since I need to receive data back, I attempted to switch to using the GET method instead. The previous implementation using POST was successful. Unfortunately, using GET resu ...

Conditionals in Angular 2 using Sass

Looking to apply this style with Sass or CSS: IF :host.form-control MATCHES .ng-valid[required] OR .ng-valid.required THEN :host ::ng-deep input.form-control = border-left: 5px solid #42A948; Appreciate the help! ...

How can I run global $PATH binaries as a no-home user using sudo?

When executing web-server-context-only operations, I run commands using sudo -u www-data {command}. Despite having NodeJS globally installed and in the root's path, it fails because the user www-data has a different path: /usr/local/bin. If I create a ...

Styling columns with full height using CSS Flexbox

I'm currently experimenting with Flexbox to design a basic two-column webpage that stretches across the entire width and height. The left column has a fixed width of 200px, while the right column uses up the rest of the space. Here's what I have ...

Boost website performance with Google Page Speed by optimizing CSS above the fold using this innovative Bootstrap Template Plugin

My Google PageSpeed Insights report suggests that I should place my CSS below the fold. However, Bootstrap is being used as my templating plugin. I am contemplating printing bootstrap.min.css inline on my homepage, but I hesitate because it may lead to i ...

Setting up a local development environment for AngularJS

I have been using the boilerplate https://github.com/node90/angular-starter as a foundation for my projects. However, I've noticed that the repository utilizes gulp to consolidate the js files in the 'app' folder into the 'public/js&apo ...

Choose links in the div and apply "motion effects."

Can anyone help me figure out why the color change for links in a div on mouseover/mouseout isn't working? Here is the HTML code: <div id="Navigation"> <a href="#">Products</a> <a href="#">Pro ...

Updating multiple divs with the same class using different values returned from an AJAX success callback in jQuery

Consider a scenario where there is a group of div elements like <div class="size"></div> <div class="size"></div> After an AJAX post request successfully returns the following data. $.each (data, function (bb) { // data is return ...

Materialize CSS is throwing an error: 'velocity is not a function'

Encountering an issue with Materialize CSS. A JavaScript error appears 'I('.velocity is not a function', for certain actions. For instance, clicking the collapse icon on the sidenav results in e.velocity is not a function error. Similarly, u ...