When the click function is triggered, it adds a class to a tag and then subsequently removes it

I attempted to create a click effect on the category using jQuery. Here is my code:

$('document').ready(function() {
        $('.links a').click(function(e) {
            e.preventDefault();
            $('.links a').removeClass('active');
            $(this).addClass('active');
        });
    });

And in the HTML:

<div class ="links">
        <a id="section-<?=$arParams['CODE']?>-link" href="#" onclick="ajax_load('#no-scroll-items-<?=$arParams['CODE'];?>', '<?=$arResult['AJAX_CALL_ID']?>', 'do=select_section&id=<?=4610?>'); return false;" class="" title="Mobile Phones">Mobile Phones</a>
        <a id="section-<?=$arParams['CODE']?>-link" href="#" onclick="ajax_load('#no-scroll-items-<?=$arParams['CODE'];?>', '<?=$arResult['AJAX_CALL_ID']?>', 'do=select_section&id=<?=4611?>'); return false;" class="" title="Tablets">Tablets</a>
        <a id="section-<?=$arParams['CODE']?>-link" href="#" onclick="ajax_load('#no-scroll-items-<?=$arParams['CODE'];?>', '<?=$arResult['AJAX_CALL_ID']?>', 'do=select_section&id=<?=4616?>'); return false;" class="" title="Monopods">Monopods</a>
        <a id="section-<?=$arParams['CODE']?>-link" href="#" onclick="ajax_load('#no-scroll-items-<?=$arParams['CODE'];?>', '<?=$arResult['AJAX_CALL_ID']?>', 'do=select_section&id=<?=4630?>'); return false;" class="" title="Headphones">Headphones</a>
        <a id="section-<?=$arParams['CODE']?>-link" href="#" onclick="ajax_load('#no-scroll-items-<?=$arParams['CODE'];?>', '<?=$arResult['AJAX_CALL_ID']?>', 'do=select_section&id=<?=4739?>'); return false;" class="" title="Media Players">Media Players</a>
        <a id="section-<?=$arParams['CODE']?>-link" href="#" onclick="ajax_load('#no-scroll-items-<?=$arParams['CODE'];?>', '<?=$arResult['AJAX_CALL_ID']?>', 'do=select_section&id=<?=4593?>'); return false;" class="" title="Accessories">Accessories</a>
    </div>

The functionality is not working correctly. Here's an example: http://jsfiddle.net/fDZ97/ What did I miss?

Answer №1

It seems like you are inquiring about toggling

$(function() {
  var $links = $('#links a').click(function(e) {
    e.preventDefault();
    $links.not(this).removeClass('active');
    $(this).toggleClass('active');
  });
});

function Animate2id(id) {
    // your function stuff
}
.active {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="links">
  <a class="active" href="#" onClick="Animate2id('#box1');">Content 1</a>
  <a href="#" onClick="Animate2id('#box2');">Content 2</a>
  <a href="#" onClick="Animate2id('#box3');">Content 3</a>
</div>

Answer №2

Your code in action:

$('document').ready(function() {
    $('#links a').click(function(e) {
        e.preventDefault();
        if($(this).hasClass("active")){
            $(this).removeClass('active');
        }else{
            $('#links a').removeClass('active');
            $(this).addClass('active');
        }  
    });
});

Try out the JSFiddle demo here

Based on my understanding, your goal is to toggle the active class when clicking. The provided code should meet your requirements.

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

Encountering this error message while attempting to synchronize an Ionic Angular project in Xcode using npx cap sync

Every time I try to run npx cap sync on my Ionic Angular project in Xcode, I encounter the following error. [!] The plist file at path `/Users/user/Documents/GitHub/project-name/ios/App/App.xcodeproj/project.pbxproj` doesn't exist. I face the ...

Updating the AngularJS view following a deletion process

I have a web application developed using AngularJS and Rails that carries out RESTful operations like create, read, and delete. After deleting an item, I need to refresh the page and update the view asynchronously. However, I am facing challenges in imple ...

What is the best way to create an animated, step-by-step drawing of an SVG path

I am interested in creating an animated progressive drawing of a line using CSS with SVG/Canvas and JS. You can view the specific line I want to draw here <svg width="640" height="480" xmlns="http://www.w3.org/2000/svg"> <!-- Created with cust ...

What is the best way to access an email link from an existing browser window?

Currently in the process of creating a Signup/Verify Email system. Here is how it works: User signs up on a webpage at /Signup.aspx and provides their email address (they are instructed to check their email). They receive an email titled "Verify your ema ...

Retrieve all information from a JSON array

Encountering a minor issue with a basic task. Here is the code snippet in question: JavaScript code Currently able to access the first object element, however, I require all the data objects. I suspect that a modification is needed in this particular cod ...

Sequelize synchronization does not generate the database table

I am currently working on a project with the following directory structure: ├── index.ts ├── package.json ├── package-lock.json ├── src │ ├── controllers │ ├── models │ │ └── repository.ts │ ├ ...

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

When a JavaScript code snippet is pasted within a <pre> tag, it will

I've been attempting to insert a JavaScript code snippet into a specific <div>. Even after wrapping the code in pre and code tags, the code ends up being executed when I try to run it. This outcome is definitely not what I had in mind. ...

Guide to sending JSON data through the Wufoo Entries API

It seems the current documentation is lacking in detailing the proper procedure for submitting forms via Ajax. Although there is The Entries POST API, it specifically discusses xml and lacks an example payload. Upon further investigation, I discovered Wuf ...

"PHP Dilemma: Navigating the Ajax Button Press Situation

I've been attempting to create a button that triggers a PHP script on a webpage and updates only a specific div tag, but so far I haven't had any success. Removing the $ajax section of the script allows my buttons to change states, but as soon as ...

Deploying static files with Django in a production environment

My Django application is functioning properly on Ubuntu 14.04 with nginx 1.10, Django 1.10.2, and uWSGI 2.0.14. It is able to load static files such as JavaScript, CSS, and images, but the CSS files are not being applied to my website. Below is the configu ...

The AJAX request is failing to work in the keypress event

When typing in a <textarea>, I want to trigger an ajax request on keypress. Specifically, when the key pressed is enter (key code = 13), the ajax request should be initiated. This is my current implementation: $(document).keypress(function(e) { ...

The comparison between exposing and creating objects in a Nodejs router file

Recently, I began using expressjs 4.0.0 and was impressed by the express.Router() object. However, a dilemma arose when I moved all my routes to another file - how do I expose an object to the routes file? In my server.js file: ... var passport = ...

Remove any words that are not included in the specified list

Here is the code snippet to achieve the desired functionality: const { words } = require("../../json/words.json") const args = message.content.split(' ') const wordss = words.filter(m=> m.includes(args)) if(args > 1 || !wordss) { ...

Transforming "datetime-local" into java.sql.Timestamp

I am working on a JSP page that has a form containing an input field with type "datetime-local". The data from this form is then passed to a servlet using the following code: String resetTimeString = request.getParameter(RequestParameterName.RESET_TIME); ...

a single function spread across two controllers[JavaScript]

My query pertains to a JavaScript program with 2 controllers. The issue I am facing is the need for one function in both controllers (data.duration). This function serves two purposes, once for features themselves and once for the summary. Currently, this ...

Exploring differences: map versus concatMap

I'm struggling to grasp the distinction between concat map and map. In a particular scenario, this difference became very confusing for me: const domainsObservable = this.auth.getAuthDomains() .shareReplay() .concatMap((authDomains) => aut ...

Retrieve the file by utilizing a token-driven API

Currently, I am in the process of developing a web application utilizing Vue.js for the front end and Laravel for the back end. The architecture of the app involves communication with the back end through api routes. Authentication is handled by passing re ...

Sorting through items based on several URL parameters

In an effort to be concise yet clear, I am working on an ecommerce website using Next.js and Shopify. This site features products that need to be filterable based on certain attributes. I retrieve products from the Shopify API, each with its own Product Ty ...

choose image for select box background

Similar Question: Background Image for Select (dropdown) does not work in Chrome I am trying to update the background image of a select box to https://www.google.com/images/nav_logo101.png Currently, I am using the following code: <form> & ...