Modify the background color attributes within the provided array

Pagination functionality: I am looking to modify the background color when a user clicks on any element within an array. Currently, the code below allows me to achieve this effect. However, I would like the previously clicked element and all other elements in the array to revert back to their original styling with the class pagins. Any suggestions on how I can accomplish this?

.pagins a {
 color: #fff;
 background-color:#009de0;
}

.testClass {
 background-color:#fff !important;
 color:#009de0 !important;
}
var elements = document.getElementsByClassName('pagins');
$.each(elements, function(){
    $(elements).click(function(){
        $(this).addClass('testClass');
    });
})

Answer №1

Avoid using $.each(), as it can cause the click handler to be called multiple times per click when looping in jQuery.

Since you are already using jQuery, opt for $('.pagins') instead of

document.getElementsByClassName('pagins')
.

If you only want the most recently clicked .pagins element to have the testClass class, make sure to remove the class from all other .pagins.testClass elements before adding it to the clicked element.

$('.pagins').click(function(){
    $('.pagins.testClass').removeClass('testClass');
    $(this).addClass('testClass');
});

Answer №2

Make sure to eliminate the testClass from every element prior to appending it to the chosen element.

  $.each(elements, function(){
        $(elements).click(function() {
            $(elements).removeClass('testClass');      
            $(this).addClass('testClass');                                          
        });
    });

Answer №3

const allPages = document.getElementsByClassName('pagination');
$.each(allPages, function(){
    $(allPages).click(function(){
        $.each(allPages, function() {$(this).removeClass('active')});
        $(this).addClass('active');                                          
    });
})

Answer №4

To streamline your code, you have the option of simplifying it like so:

$(".testClass").removeClass("testClass");
$(".pagins").click(function() {
    $(this).addClass('testClass');
});

This method works by assigning a click function to all elements that share a specific class selector.

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

Unable to adjust the size of the icons sourced from https://github.com/erikflowers/weather-icons

While integrating openweathermap with these icons, I encountered an issue where I couldn't adjust the size of the icons. They are used similarly to font-awesome icons, like this: <i class="wi wi-omw-100"></i> I have tried changing various ...

What causes the excess spacing in flexbox containers?

Is there a way to remove the padding around the container and between the two columns? I attempted setting margin and padding to 0, but it was not successful. https://i.sstatic.net/i5XJJ.jpg body, html { width: 100%; height: 100%; } main { disp ...

Changing the image source attribute with jQuery

I'm attempting to create a function where the image changes based on each click. Essentially, I want alternating clicks to display different image sources, similar to a slideToggle effect. While researching, I found that some individuals utilize toggl ...

Retrieve the bounding rectangle of a div that has the CSS style `display: contents` using the getBoundingClientRect

My objective is to apply styling and obtain the bounding box of an entire "row" within a CSS grid, including features like highlighting when hovering over it. To achieve the styling aspect, I make use of the display: contents property, so that the styles ...

How can PHP be used to group arrays that share common values to prepare them for JSON output?

I'm currently working on building an array using WordPress data // Retrieving a list of tags $custom_terms = get_terms('post_tag'); $term_all = array(); $cats_all = array(); foreach($custom_terms as $custom_term) { ...

Enhance user experience by implementing an autocomplete feature for a text input field

Can you name the process in which a form is automatically filled using database information without needing to refresh the page? One common example of this technique is seen on platforms like Google or Facebook, where they predict friends you may be searc ...

Tips for activating a sticky navigation button by scrolling down slightly

Currently in the process of developing a website using React and focusing on optimizing the mobile version first. One feature I am working on is to have a sticky navigation bar that remains at the top after scrolling down. In the attached picture, there is ...

The XML data does not provide any website addresses

After inputting all possible parameters and data into a URL, XML is not being returned. The locally hosted XML works fine, but not when using a URL. HTML: <section ng-controller="AppController" class="container-podcastapp"> <ul> ...

Displaying a dynamic splash screen during the resource-loading process on an Android application

I would like to implement an animated image (currently using a set of PNGs) as a splash screen while my resources are loading. I have successfully displayed the splash screen using this method. However, the issue I am facing is that the splash screen appe ...

Harnessing the Power of React with Javascript Promises

Snippet 1 async function saveToDatabase(order, ownProps) { const url = `api_url` await axios.post(url, order).then( (response) => { if (response.status == 200){ console.log("response 200") console.log(resp ...

Converting API data to an array map in React with Typescript

There is an array data retrieved from an API that needs to be rendered in a React TypeScript file using the map function. { "data":{ "cart":{ "1":{ "product_id":1, "name":"Product 1", "quantity":1, ...

Reorganize files with sequential numbers using Gulp, starting from the highest number within the directory

I am looking to create a gulp task that moves files from one folder to another while renaming them with sequential numbers. Here is the current task I have: var index = 0; gulp.task("jpg", function () { return gulp.src('img/new/**.{jpg,JPG}&ap ...

Transfer both files and text strings to PHP using FormData

Is there a way to send strings to PHP using Ajax form data? I recently came across this code at . I am trying to figure out how to pass string data to PHP using the code provided above. I want to integrate this code into my website to enable users to upl ...

What separates the placement of "allScriptsTimeout" within and outside of "jasmineNodeOpts" in a protractor conf.js file?

When it comes to the placement of the setting allScriptsTimeout in the protractor conf.js file, there seems to be a difference whether it is inside or outside of the jasmineNodeOpts. Below are two examples for reference, but which one is considered valid? ...

The button is disabled once inline CSS is applied to it

I was having issues with the CSS of my buttons being overridden by the user agent stylesheet. To fix this, I used inline CSS to override it. However, a new problem emerged where the buttons became unclickable. Here is the code I am using. Any assistance wo ...

What could be causing my HTML form placed within a jQuery-UI dialog to fail submitting?

Displayed here is the HTML form code as seen on Firebug: <form action="http://localhost/home/newuser" method="post"> <input type="hidden" value="48" name="user_id"> <input type="text" name="username"> <input type="submit" ...

Which option is more suitable for my needs: utilizing an array or an sqlite database

I am in need of guidance as I work on creating an app. Although I have no prior experience with android app development, I am dedicating time to studying and practicing. The goal is to develop an app that allows users to record payments from a customer li ...

Tips for implementing a time delay before copying a message in Discord.js and node.js to account for edits made after a few seconds

I have a script that is currently copying messages from my main server to the secondary server. However, I need to introduce some delay as sometimes I edit embeds and it ends up sending the unedited message first. Is there a way I can delay getting both ...

Align the video element to the top left corner using Bootstrap 4

Just getting started with bootstrap and css. I'm trying to insert a video element into a row class and want it to be positioned at the top left of the row without any margins. Currently, the video is centered vertically with space above it. Ideally, ...

Why is the value retrieved from e.target.parentNode.children[0].innerText always different from the value returned by the filter function?

My approach to deleting items from the ToDo list using event delegation involved placing a delete onClick handler on the ul element. However, I encountered an issue where toDo != e.target.parentNode.children[0].innerText never evaluates to true, despite ...