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

Vivaldi's performance gradually slows down as Ajax calls take longer to load before the page finally refreshes

I have a question regarding my JavaScript/jQuery application. I am making an Ajax call in the following way: var startTime = new Date().getTime(); $(target).load(url, function() { var endTime = (new Date().getTime() - startTime) / 1000; console.log(&qu ...

Ways to extract values from a javascript hash map by exclusively incorporating an array

So here's the issue I'm encountering. Let's consider the following scenario: let surfaces: Map<any, any> = new Map([{"83.1" => Object}, {"84.1" => Object}]) let arr1 = ["83.1"] This is the desired o ...

Error sound produced when detecting KeyCode on the keyboard

I'm currently working on a JavaScript project that involves capturing keyboard input. However, I'm encountering an issue where every time the user presses a key, it triggers an error sound. Is there a way to disable this sound? ...

Transfer the @font-face declaration from the global CSS file into the MUI Theme

In my project, I have an index.css file that includes the following @font-face declaration: //Index.css ... @font-face { font-family: "My Font"; font-style: normal; font-display: swap; font-weight: 400; src: url(/public/fonts/my-font.eo ...

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

The Sequelize error message states: TypeError: an array or iterable object was expected, but instead [object Null] was received

I am encountering an issue with the findOne method from sequelize in my model. The error message I am getting states that the table referenced by the model is empty. How can I resolve this? Unhandled rejection TypeError: expecting an array or an iterable ...

Encountered a 404 error while trying to delete using VueJS, expressJS, and axios. Request failed with

Currently, I'm in the process of learning the fundamentals of creating a MEVN stack application and facing a challenge with the axios DELETE request method. The issue arises when attempting to make a DELETE request using axios, resulting in a Request ...

Triggering a fancybox by selecting an option from a dropdown menu and sending the chosen value to it automatically

<select name="mySelectboxsituation_found" id="mySelectboxsituation_found"> <option value="100">Firecall</option> <option value="200">FireAlarm</option> <option value="300">FireAlarm2</option> <option value="4 ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...

Using jQuery to harness the power of a single event for multiple controls

Looking to condense some code here, let me explain further. I currently have multiple Button controls each with individual click events assigned to them. $(".button").click(function() { var v1 = $(this).attr('id'); switch(v1) { ...

With Crypto-JS, a fresh hash is always generated

I'm looking to integrate crypto-js into my Angular 8 application. Here is a snippet of my code: import {Injectable} from '@angular/core'; import * as CryptoJS from 'crypto-js'; @Injectable() export class HprotoService { public ...

PHP: Dynamically update div content upon submission

I am attempting to update the "refresh" div after clicking the Submit button and also at regular intervals of 5 seconds. Despite looking through various resources, I have not been able to find a solution that meets my requirements. <script src="h ...

Problem with Internet Explorer version 9 and above and the Flip Card feature

I have a cool feature for one of my clients where clicking on one div causes another div to flip in its place, like a card flipping over. It's kind of like those portfolio image flippers, but instead of images, it flips divs with content inside. How ...

Convert PHP MySQL REQUESTED DATE to XML format and display it on an HTML page

I've been browsing tutorials throughout the day, but have been unsuccessful in finding exactly what I need. My goal is to save strings in MySQL such as: - Name - Location - Type - Price What I'm looking for is a way to extract specific data and ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

What is the best way to transform an array of arrays into an array of objects using AngularJS?

Here is some code I am working on: $scope.students=[]; $scope.students[[object Object][object Object]] [0]{"id":"101","name":"one","marks":"67"} [1]{"id":"102","name":"two","marks":"89"} I would like to reformat it into the ...

Is it possible to delete an element from both local storage and HTML by referencing its ID?

Experience a simple flashcard game where you enter a question and answer to create a new flash card stored as an object within the cards array. The newly created flash card is also displayed by appending a new element to the flash cards section on the webp ...

Smooth scrolling for the entire webpage using jQuery

Does anyone know how to create a seamless mouse scrolling effect, similar to what is seen on this website? Check it out here: I have looked online, but haven't been able to find a satisfactory solution for this problem. ...

Deliver data in batches of ten when the endpoint is accessed

I am currently in the process of developing a web application using Next.JS and Node. As part of this project, I have created my own API with Node that is being requested by Next.JS. One particular endpoint within my API sends data to the front end as an ...

Troubleshooting Problem with JQuery in the YouTube Player API

Having some difficulty parsing YouTube video ids to a function that plays them in an embedded player using a combination of JavaScript and jQuery with the YouTube Data and Player APIs. Below is my code: <html> <head> <script src="//aj ...