Ways to display one element while concealing it when another is clicked

I am utilizing a series of div elements that can be triggered with the following code snippet:

$(".course_id").on("click", function(){
         var id = $(this).data("id");
         $("div#lessons_by_course_" + id).removeClass("hidden");
    });
    

The div elements are assigned with an id like lessons_by_course + id, for example:

<div id="lessons_by_course1"></div>
    

The ID number is dynamically generated using a Ruby on Rails .each loop.

My goal is to have only one div visible at a time. So when I click on a certain div, I want it to display and hide the previously shown div. This way, only the clicked div will be visible.

Keep in mind that .course_id is a class applied to multiple elements, causing different divs to appear each time one of them is clicked due to the unique ID being utilized for each element.

Answer â„–1

One way to optimize performance is by storing the ID of the most recently displayed element in a global variable:

var latestId;

Then, within your loop:

$(".course_id").on("click", function(){
    if(latestId) {
        $("div#lessons_by_course_" + latestId).addClass("hidden");
    }
    latestId = $(this).id;
    $(this).removeClass("hidden");
});

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

Ways to eliminate text following a string substitution

When running the code below with keys assigned to summer, spring, fall, and winter, the output for ins would be: ['req.body.summer, req.body.spring, req.body.fall, req.body.winter'] I need to eliminate the surrounding string from the replace co ...

"What's the best way to update the src attribute of an iFrame when a user clicks

I'm new to coding in PHP or JavaScript, so please bear with me if my question isn't quite right. I'm looking for a way to dynamically pass and embed a URL from a link into the src attribute of an iframe. Essentially, I want users to click o ...

Switching the visibility of rows in a table

Imagine this as my example table: <table> <tr> <td>a</td> <td>one</td> <td>two</td> </tr> <tr> <td>b</td> <td>three</td> <td>four</t ...

Choosing Only the Visible Element with CSS

Within my program, there exists a text element that appears in two distinct sections: section A and section B (in the form of a popup). My intention was to create one object using CSS that could be utilized in both areas. By doing so, I would be able to em ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

Implementing Othello Minimax Algorithm in React.js Yields Unsuccessful Results

I need assistance with a recurring issue where the AI player consistently plays the first available move it encounters. My objective was to implement an AI using the Minimax Algorithm, but I'm facing challenges in achieving the desired functionality. ...

The express-fileupload throws an error saying "ENOENT: unable to locate the file or directory at 'public/images/name.ext'"

I am encountering an error ENOENT: no such file or directory, open 'public/images/name.ext from express-fileupload. I have searched for solutions to this issue, but none of the ones I found seem to work for me. Here are two examples: No such file or d ...

Verify whether the variable is defined or present within the Angular controller

In my Angular controller, I have the following function: $scope.sendCompanyData = function() { delete $scope.company["step1Form"]; delete $scope.company["step2Form"]; delete $scope.standard_address["state"]; $http.post(Routing.generate(&a ...

Creating an easy-to-update catalog utilizing an external file: A step-by-step guide

I am looking to create a product catalog with 1-4 products in a row, each displayed in a box with details and prices. I would like to be able to generate the catalog easily using an XML/CSV file that can be updated. Can anyone provide guidance on how to ac ...

"Utilize the power of the ajaxform jQuery plugin to automatically reset form fields

Initially, I'd like to emphasize that this is an original inquiry. My predicament is as follows: I have a chatroom php script where I utilize the ajaxForm jQuery plugin to seamlessly send new messages without having to reload the entire page. Howev ...

Distinctive titles for JavaScript constructors/prototypes compared to classes

When working with JavaScript ES6, classes allow us to write code like this: class RectangularShape { constructor(height, width) { this.height = height; this.width = width; } getArea() { return this.height * this.width } static some ...

What causes Google fonts to fail on Heroku but succeed when used locally?

I am currently using express and heroku to host a prototype of a landing page. While the webpage functions properly when running locally, I encounter font loading issues when accessing it on heroku most of the time... The CSS files are located under /pub ...

Methods for anchoring an element at the bottom of a square container div

* { box-sizing: border-box; } .publication { display: flex; width: 100%; margin-top: 6%; } .bottom1, .bottom2 { display: flex; flex-direction: column; ...

Error encountered during post-installation process for package `[email protected]`. The script `node scripts/build.js` failed to execute, resulting in an exit status of 1

Whenever I run the gulp serve command for my AngularJS Fuse project, I encounter this error. C:\wamp\www\bank_admin_post_login\Fuse-1.4.1-demo>gulp serve C:\wamp\www\bank_admin_post_login\Fuse-1.4.1-demo>npm rebuil ...

Modifying multiple objects with Vue's V-Model

When utilizing the mounted function in Vue to assign two different objects in the data area and bind one of them to a form, an unusual issue arises: Both objects change when input values are entered in the form For example: <template> <v-card ...

Python Selenium: How to locate elements using xpath in the presence of duplicate elements within the HTML code

Currently, I am utilizing selenium to extract data from a liquor sales website to streamline the process of adding product information to a spreadsheet. My workflow involves logging into the website using selenium and searching for the specific product. Wh ...

Unlimited scrolling: Fetching additional data via an Ajax request?

I am working on setting up a table with infinite scroll functionality to showcase user information such as name, address, and email. To accomplish this, I began by importing the json-server package and creating an API endpoint using fakerjs in a separate f ...

Error encountered while making an http get request for a node that returns JSON

I've been struggling with this issue for quite some time now. While I've come across similar problems on Stack Overflow, none of the suggested solutions seem to work for me. I keep encountering the following error message: undefined:1 SyntaxErro ...

How to Make Buttons Vanish and Reappear

Check out this fiddle for a picture button 'scroller' that I created. It may not be perfect, but my main focus is on making the arrow buttons fade in and out when reaching the end of the picture order. I am considering using a JavaScript functio ...

PHP-generated interactive pie chart

I'm encountering a puzzling issue while attempting to create a pie chart in Flot using data from PHP. The chart seems to be rendering incorrectly, and I'm struggling to identify the cause. Below is my PHP code (used for testing): echo json_enc ...