Tips for applying and removing classes using an anchor tag

When I click on an anchor, I want it to add a specific class.

This is my current markup:

    <ul>
        <li>
            <a href="<?php echo base_url()?>home/promos/call" class="promo-call"></a>
        </li>
        <li>
            <a href="<?php echo base_url()?>home/promos/text" class="promo-text"></a>
        </li>
        <li>
            <a href="<?php echo base_url()?>home/promos/data" class="promo-data"></a>
        </li>
        <li>
            <a href="<?php echo base_url()?>home/promos/combo" class="promo-combo"></a>
        </li>
        <li>
            <a href="<?php echo base_url()?>home/promos/recent" class="promo-recent"></a>
        </li>
    </ul>

For example, when clicking on class="promo-call", I want it to add class active-call. Similarly, clicking on promo-text should add class active-text.

Just to clarify my intention:

For instance, when promo-call is clicked:

<a href="<?php echo base_url()?>home/promos/call" class="promo-call active-call"></a>

When promo-text is clicked:

<a href="<?php echo base_url()?>home/promos/text" class="promo-text active-text"></a>

Similarly, for promo-data and others.

Additionally, when one anchor is active, the rest should return to their original class and be inactive.

Currently, my code looks like this:

It's still in the trial and error phase. I'm currently working on promo-call and promo-text only. A strange issue I'm facing is having to click the button twice for the background image to show.

jQuery(document).delegate(".promo-call","click",function(e){   
  jQuery(".promo-text").removeClass("active-text");
  jQuery(".promo-call").addClass("active-call");
});

jQuery(document).delegate(".promo-text","click",function(e){  
    jQuery(".promo-text").addClass("active-text");
    jQuery(".promo-call").removeClass("active-call");
});

Just to let you know, I'm using jQuery-Mobile.

Answer №1

Give this a shot:

let promoButtons = $('a[class^="promo"]');

promoButtons.on('click', function(event) {   
    event.preventDefault();
    promoButtons.removeClass('active-text active-data active-call ...');
    $(this).addClass(this.className.replace(/^promo/, "active"));
});

Keep in mind that in

promoButtons.removeClass('active-text active-data active-call ...');
you must list out all active classes you want to use.

Alternatively, you can use a single unique "active" class (e.g. active) instead of multiple different active classes: if this is purely for styling purposes, you can style your links using a single class like this.

.promo-text { ... }
.promo-text.active { ... }

.promo-data { ... }
.promo-data.active { ... }

By following this approach, you can simplify both your CSS and JavaScript code by only needing to apply a toggleClass('.active') to all links.

Answer №2

$('a[class^="promotion"]').on('click', function() {

   $.each('a[class^="promotion"]', function() {
       $(this).attr('class','');
   });

   var currentClassName = $(this).attr('class');

   if(currentClassName)
   {
       var startClassName = string.split('-');

       if(startClassName.length > 1)
       { 
          $(this).toggleClass('active-' + startClassName[1]);
       }
   }
});

It is important to note that this code is designed for single-classed elements similar to the example provided.

Answer №3

By using .toggleClass("promo-call"), achieving this outcome is possible

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

Fill a .js script with moustache.js

I need help with organizing some JavaScript code that needs to access server-side data. I want to keep this code in a separate .js file, but I'm having issues populating it with the necessary server information using moustache. Here is my current setu ...

What is the best way to conceal the standard 'X' close button within a magnific popup interface?

I implemented the Magnific-popup plugin in my jsp to show messages to users. Here is the code I used to open Magnific Popup: $.magnificPopup.open({ items: { type: 'inline', src: '#idOfSomeDivInPage' }, focus: '#some ...

What is the reasoning behind beginning the transition with autofocus enabled?

After creating a contact form with autofocus="autofocus", a strange behavior was noticed. It seems that when the form has autofocus, the transition effect on the navigation bar is triggered in Firefox only. Is this an error on my end or just a bug specific ...

Unable to attach a javascript eventListener to a newly created element

I've utilized JavaScript to generate 625 <div class="box"><div> elements and now I'm trying to attach an event listener to each box. The boxes are being created successfully, however, the listener does not seem to be working ...

Is there a way to turn off _moz_resizing on my browser?

I am currently using the nicEdit editor and have successfully integrated my own custom image resizing script. However, I am facing an issue where the default _moz_resizing feature in Firefox is interfering with my custom script. My goal is to have specifi ...

tips for linking my webpage with the database

While working on a registration page, I encountered an issue where the entered information was not being stored in the database. Instead, an error message appeared: Notice: Undefined variable: sql in C:\xampp\htdocs\Bawazir\Untitled-1. ...

Why is this regular expression failing to match German words?

I am attempting to separate the words in the following sentence and enclose them in individual span elements. <p class="german_p big">Das ist ein schönes Armband</p> I came across this: How to get a word under cursor using JavaScript? $(&ap ...

Issue with FiFO on MacOs causes skewed borders to not display correctly

I am currently facing an issue with my webpage and would greatly appreciate some help from the community. My goal is to create a skewed border inside a div, similar to the example on this JSFiddle link: https://jsfiddle.net/kx6f9rsd/ .container { backgro ...

Issues with the .change(function() JavaScript in Internet Explorer versions less than 9

I'm experiencing issues with this script in Internet Explorer versions below 9. Can someone please help me identify what is wrong with my script? Thank you. IE7 and IE8 are showing the following error: SCRIPT87: Invalid argument. Found ...

The OTP submission in Phone Email's phone authentication using Node JS did not result in the reception of the token

I have implemented the “Login with Phone” Button from Phone Email on my Node JS website. The button opens a popup to enter the mobile number and then displays an OTP window after submission. Although I receive the OTP SMS and enter it successfully, I a ...

The error message received is: "mongoose TypeError: Schema is not defined as

Encountering a curious issue here. I have multiple mongoose models, and oddly enough, only one of them is throwing this error: TypeError: Schema is not a constructor This situation strikes me as quite odd because all my other schemas are functioning prop ...

Get a Blob as a PNG File

Hope you had a wonderful Christmas holiday! Just to clarify, I am new to JS and may make some unconventional attempts in trying to download my Blob in PNG format. I am facing an issue with exporting all the visual content of a DIV in either PDF or image ...

Identify the individual who accessed a hyperlink within an email

My team is planning a small experiment involving sending an email to around 50 employees. The email will contain a link to a website stored on our local server, and I want to be able to track exactly who clicks the link by matching it with their email addr ...

The use of the tooltip function in Rails 6 webpack may not be possible

I have attempted to modify the versions of bootstrap, jquery, and popper without success. I do not believe I am utilizing multiple versions of jquery. I am uncertain as to where the issue may lie. Any assistance in identifying what I may be overlooking wou ...

Guide on creating a toggle effect for a div with querySelector and addEventListener

I utilized the email and password divs provided by Bootstrap. The CSS for the id dropdownlogin includes display: none; in this post, I hope that I have shared adequate information. <script> document.addEventListener('DOMContentLoaded', ...

Tips for incorporating Action Links into your CSS workflow

<li class="rtsLI" id="Summary"><a href="javascript:void(0);" onclick="javascript:rtsXXX.OnClientTabSelected(this‌​, 0);" class="rtsLink"><span class="rtsTxt">Test</span></a></li> I have made a change by replacing th ...

Using feature flags in Vue for enhanced functionality

I am interested in incorporating a "feature toggling mechanism" into my Vue application. Although I have set up a basic system, I want to explore the methods outlined in a article by Pete Hodgson. The concept of "Inversion of Decision" seems particularly i ...

A linear gradient effect originating from the center/middle of the background

Is it possible to create a linear-gradient background that starts from the center or middle of the screen? This is the CSS I am currently using: body { display: table; width: 100%; height: 100%; margin: 0 auto; background-repeat: no-r ...

Invalid Data Pusher for User Information in Next JS

Hello everyone, I've been practicing using Pusher with Next.js but encountered an issue where it's showing Error: Invalid user data: 'presence-channel' and I can't seem to solve it no matter how hard I try. Could someone please he ...

Multer is not recognizing the uploaded file and is returning req.file

This question has definitely been asked multiple times in the past, and I have attempted to implement various solutions without much success. Struggling to upload a file and read its size through Node has left me frustrated. Initially, I tried using the f ...