Ways in which elements can be toggled through jquery or javascript?

There are various words listed below:

word1 word2 word3 ...

Every word in the list is linked to 1 to 3 examples. When a user clicks on a word, certain actions should take place.

  1. I want the examples to display when the associated word (e.g., word1) is clicked.
  2. If another word is clicked, the displayed examples should automatically hide.
  3. If word1 is clicked again, the examples should be hidden.

Below are the code snippets:

HTML

<a>word1</a>
<div class="sents">
    <li>This is the first example</li>
</div>

<a>word2</a>
<div class="sents">
    <li>This is the second example</li>
    <li>This is the second example</li>
</div>

<a>word3</a>
<div class="sents">
    <li>This is the third example</li>
    <li>This is the third example</li>
    <li>This is the third example</li>
</div>

Script

$(document).ready(function () {
    $('a').click(function () {
        $('a').next('div').removeClass('active');
        $(this).next('div').toggleClass('active');
    });
});

CSS

a:hover {
    background-color: yellow;
}

.sents {
    display: none;
}

.active {
    display: block;
    position: absolute;
    background-color: yellow;
    width: 100%;
    padding: 5px;
}

You can view the demo here.

I'm not very familiar with javascript/jquery. Thank you for your assistance in advance.

Answer №1

The issue arises when you eliminate the .active class from all of the div elements (including the one that should toggle) and then the toggleClass function simply adds it back, resulting in the targeted div always being visible.

To resolve this, utilize the siblings() selector function:

$(document).ready(function () {
    $('a').click(function () {
        $(this).next('div').siblings().removeClass('active');
        $(this).next('div').toggleClass('active');
    });
});

View the working demonstration here: https://jsfiddle.net/umxf19vo/24/

Answer №2

It appears that your code is almost functional, but there is an issue with hiding the examples when the same word is clicked. To address this issue, you need to first determine the current state of the word that was clicked. The solution is to only set it as active if it wasn't already in that state.

You can check the current state by using the hasClass('active') method. Since you are conditionally adding the class, you can simply use addClass('active') within an if statement.

Another approach would be to utilize toggleClass('active', !isActive). However, if you choose this option, clicking on a word to deactivate it would result in attempting to remove a class that had already been removed. This unnecessary interaction with the DOM can be prevented by using an if statement instead.

$(document).ready(function () {
    $('a').click(function () {
        var isActive = $(this).next('div').hasClass('active');
        $('a').next('div').removeClass('active');
        if (!isActive) {
          $(this).next('div').addClass('active');
        }
    });
});
a:hover {
    background-color: yellow;
}
.sents {
    display: none;
}
.active {
    display: block;
    position: absolute;
    background-color: yellow;
    width: 100%;
    padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>word1</a>

<div class="sents">
    <li>This is a first example</li>
</div>
<a>word2</a>

<div class="sents">
    <li>This is a second example</li>
    <li>This is a second example</li>
</div>
<a>word3</a>

<div class="sents">
    <li>This is a third example</li>
    <li>This is a third example</li>
    <li>This is a third example</li>
</div>

Answer №3

Give this a shot

$(document).ready(function () {
    $('a').click(function () {
        if ($(this).next('div').hasClass('active')){
            $('.sents').removeClass('active');
        }
        else{
            $('.sents').removeClass('active');
            $(this).next('div').addClass('active');
        } 
    });
});

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

jsonwebtoken does not fetch a token

I've been working on a user registration system using nodejs and sequelize. So far, I've successfully implemented the login and register functionalities. However, I am encountering an issue with getting the token after a successful login. Despit ...

When utilizing NavLink in React Router Dom for routing to an external link, a local host is automatically included in the prefix

I'm currently experiencing an issue with routing to an external link using React Router Dom 6.4. It seems that the localhost path is being appended to the URL. Can anyone provide insight on why this might be happening? localhost:3000/#/http://www.sav ...

The most efficient way to invoke a jws void method in the fewest steps possible

When calling a void method of a SOAP JWS web-service using JavaScript without expecting a result back, what is the most efficient and concise approach? ...

Transmit information to php script using an html document format

Is there a way to load the file table.php with the data that I am trying to pass when the ajax call is made? I have attempted to do this using the jquery.load method, where the second parameter is a data array, but it doesn't seem to be working. Here ...

Changing an ng-repeat filter following the manual update of a text input

Utilizing jQuery auto-complete to automatically populate values as users type into a text input. <input type="text" ng-model="tags" name="tags" id="tags" value="" /> Subsequently, the ng-repeat is filtering content based on the entered text <di ...

Include onload to element without running it in Puppeteer

I am currently developing a web scraping tool using Puppeteer. Once the webpage is fully loaded, I need to update the HTML code and include an onload event for certain elements. The issue is that in Puppeteer, the onload event is actually triggered automa ...

Creating a series of scalable svgs of uniform size in a row, enabling me to resize them based on width without disrupting the overall design

I need a row of equally sized SVGs with some text below them, like a navigation bar but larger. I almost have it working, but there are some issues with my current setup. To clarify, this is what I am aiming for: The SVGs should be responsive and scale a ...

What methods can be utilized to accurately determine a user's online status without continuously sending AJAX requests to the server through setInterval?

Seeking effective methods to determine a user's online status I am currently employing an inefficient technique to address this issue: I continuously send AJAX requests to the server at set intervals using setInterval, allowing the server to gauge th ...

The Upstash Redis scan operation

Attempting to utilize the @upstash/redis node client library for Node.js (available at https://www.npmjs.com/package/@upstash/redis), I am facing challenges in executing the scan command, which should be supported based on the documentation. Specifically, ...

Preserving the <script> tag when defining HTML code

During an AJAX call, I am receiving plain HTML with some JavaScript code. When I try to display this response in a container using .html (jQuery) or innerHTML (plain JavaScript), it removes the <script> tag and all JavaScript code. However, when I c ...

Uncovering the inherent worth of an item pulled from a remote location using Vue.js

Currently, I am retrieving a list of countries by making an API call in VueX. The fetched data is then stored in a state using a mutation. Essentially, the countries are saved in a variable known as this.$state.getters.countryList, which can be accessed f ...

The age calculator is failing to display the accurate age calculation

This code is designed to compute the age based on the selected value in the combo box, and display the result in the text box below. The age should update every time the user changes the selected value in the combo box. However, the computed age is not cur ...

Is it feasible to customize the css3 resize feature?

I'm curious - is there a way to customize the CSS3 resize property? div { resize: both; overflow: auto; } Basically, I am looking for a horizontal resize with a vertical bar instead of the default handle. Take a look at the images for reference. ...

The flow of browsing the web and executing scripts in a web browser

I'm really struggling to grasp the logic behind this function I'm working on. public void PortalLogin(AutoResetEvent signal) { // Navigate to portal string portalUrl = "website_name"; ...

Issue in Ionic 2: typescript: The identifier 'EventStaffLogService' could not be located

I encountered an error after updating the app scripts. Although I've installed the latest version, I am not familiar with typescript. The code used to function properly before I executed the update. cli $ ionic serve Running 'serve:before' ...

Is it possible to access a class with protected/private fields written in TypeScript from outside the class in JavaScript?

Currently, I am delving into TypeScript classes (though my experience with OOP is limited). The following code snippet is extracted from the chapter on classes in https://www.typescriptlang.org/docs/handbook/classes.html Here's the issue at hand: I ...

Delete the tag that comes before

Is there a specific tag like: <p id="name" onclick="javascript:var ele=context(this);">sumtext here</p><br> <p id="name" onclick="javascript:var ele=context(this);">newtext here</p><br> <script ...

Implement a versatile Bootstrap 5 carousel featuring numerous sliders

Is it possible to create a Bootstrap 5 carousel with six items displaying at a time instead of three? I tried changing the value in the JS code, but it didn't work. Can you correct my code so that it displays six items at a time and can be variable la ...

Having trouble with setting up ENV variables while deploying the app on Heroku

I recently deployed my node.js app to Heroku, and I'm facing some issues with its functionality. The app loads fine, but when I try to sign in, it breaks down. It seems like the environment variables are not loading correctly, specifically the db vari ...

The Angular Material Theme is not being properly displayed on the mtx-datetimepicker component

Issue: While using directives from ng-matero for DateTime with Angular Material for application design, the dateTimepicker element is not applying the angular material theme as desired. https://i.sstatic.net/zPBp3.png Code Example The app.module.ts file i ...