Using an onClick event along with jQuery to change the CSS class style of another div

After searching extensively without success, I decided to register and ask my first question here. Hopefully, someone can provide a solution:

My goal is to create a set of five buttons (divs) with onClick events that will show five different divs. I've managed to make it work using inline code for each button, but I'm looking to streamline this by creating an external function that simply sets the clicked div (which will display a yellow border) and the div that should be shown.

The structure of the code I'm attempting to write is as follows:

HTML:

<div id="button1" class="button" onClick="choose(this,'c1')"></div>
<div id="button2" class="button" onClick="choose(this,'c2')"></div>
<div id="button3" class="button" onClick="choose(this,'c3')"></div>
<div id="button4" class="button" onClick="choose(this,'c4')"></div>
<div id="button5" class="button" onClick="choose(this,'c5')"></div>
<div class="c1"></div>
<div class="c2"></div>
<div class="c3"></div>
<div class="c4"></div>
<div class="c5"></div>

JAVASCRIPT-JQUERY:

function choose(button,card) {
$( "#button1" ).css("border-color", "#F1F1F1");
$( "#button2" ).css("border-color", "#F1F1F1");
$( "#button3" ).css("border-color", "#F1F1F1");
$( "#button4" ).css("border-color", "#F1F1F1");
$( "#button5" ).css("border-color", "#F1F1F1");
$( "div.c1" ).hide();
$( "div.c2" ).hide();
$( "div.c3" ).hide();
$( "div.c4" ).hide();
$( "div.c5" ).hide();
$( button ).css("border-color", "#FFCC00");
$( div.card ).show();
}

The part where the border color changes upon clicking works well, but I'm struggling to figure out how to dynamically pass the class name of the div that should be displayed into the jQuery function, which should be one of c1, c2, c3, c4, or c5. Can anyone provide assistance with this?

A big thanks to @Roko C. Buljan for providing the best overall solution http://jsbin.com/UXElode/4/edit

Answer №1

One possible approach could be:

$("." + card).display();

Answer №2

What about simplifying your code to just include the following:

<div id="button1" class="button"></div>
<div id="button2" class="button"></div>
<div id="button3" class="button"></div>
<div id="button4" class="button"></div>
<div id="button5" class="button"></div>
<div class="c1"></div>
<div class="c2"></div>
<div class="c3"></div>
<div class="c4"></div>
<div class="c5"></div>

Additionally, you can simplify the functionality with this script:

$('.button').click(function(){
     $('.button').css("border-color", "#F1F1F1");
     $( this ).css("border-color", "#FFCC00");
     var n = this.id.split('n')[1];
     $('.c'+ n).show();
});

If you want to extract the number from the clicked ID element, you can use the following line of code:

var n = this.id.match(/\d+/g);

Check out a live demo for reference.

Answer №3

Here is an example of how you can achieve a similar result:

<div id="button1" class="button"></div>
<div id="button2" class="button"></div>
<div id="button3" class="button"></div>
<div id="button4" class="button"></div>
<div id="button5" class="button"></div>
<div class="c button1"></div>
<div class="c button2"></div>
<div class="c button3"></div>
<div class="c button4"></div>
<div class="c button5"></div>

You can use this Javascript to make it work:

$(".button").click(function(){
  $(".button").css("border-color", "#F1F1F1");
  $(".c").hide();
  $( this ).css("border-color", "#FFCC00");
  $( "."+this.id ).show();
});

Answer №4

Wouldn't it be better to code it like this?

HTML

<form id="buttons">
    <div id="btn1" style="background-color:#F1F1F1">Button 1</div>
    <div id="btn2" style="background-color:#F1F1F1">Button 2</div>
    <div id="btn3" style="background-color:#F1F1F1">Button 3</div>
     <div id="btn4" style="background-color:#F1F1F1">Button 4</div>
    <div id="btn5" style="background-color:#F1F1F1">Button 5</div>
</form>
<form id="array">
    <div class="btn1">btn1</div>
    <div class="btn2">btn2</div>
    <div class="btn3">btn3</div>
    <div class="btn4">btn4</div>
    <div class="btn5">btn5</div>
</form>

JavaScript (w/JQuery)

$('#buttons div').click(function () {
    var btnID = $(this).attr('id');
    $('.' + btnID).hide();
});

Check out the Jsfiddle demo here!

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

Sorting tables using ajax-generated data

I am having trouble with a table that is generated using ajax (PHP). Even though I have included all the necessary attributes for tablesorter, it doesn't seem to be working. Can someone please point out where I might have made a mistake? Any suggestio ...

Encountering an issue with Angular build in Docker: [ERR_STREAM_DESTROYED] - Write function cannot be called after a stream

Below is the docker file I'm using to build my Angular project: FROM node:12-buster-slim as build-step RUN mkdir -p /app COPY . /app WORKDIR /app RUN chmod 777 -R /app RUN npm install ARG configuration=production RUN npm run build -- --output-path=./ ...

Regular expressions - For alphanumeric or numeric with a possible slash character included

I need assistance with extracting alphanumeric values from a string array using RegEx. For instance: Apartment 101/B First Villa 3324/A Second Milk 12MG/ML Third Sodium 0.00205MG/ML Fourth Water 0.00205MG Fifth Eggs 100 Sixth My goal is to retrieve the v ...

Embracing Elegance with jQuery

Is there a way to customize the appearance of my list (<ul>) in the following code snippet? $.widget( "custom.catcomplete", $.ui.autocomplete, { _renderMenu: function( ul, items ) { var self = this, currentCategory = ""; ...

Trying to organize JSON data by multiple parameters using jQuery

Regarding the topic discussed in this thread; I have successfully managed to sort an Array of JSON Objects by two fields. Additionally, the discussion mentions: "To include additional columns for sorting, simply add them to the array comparison." // ...

Prevent loss of data when user incorrectly submits a webform

Currently, I am working with Wordpress and a contact form plugin which is based on php. The form provided by the plugin is quite lengthy and my client has requested that the data entered by users should not disappear if they make a mistake and need to co ...

Implementing image caching in tvOS with React-Native: A step-by-step guide

Looking to Implement Image Caching in tvOS using React Native I'm trying to figure out how to cache images that I download from the internet on my Apple TV. I've experimented with various libraries, but none seem to be compatible with tvOS. Any ...

Align text in the center of a static container

I am facing the challenge of aligning four h4 tags in the center of their respective fixed divs, all set to width: 100% to ensure their background-color: rgba(255, 255, 255, 0.5); covers the entire browser width. Despite trying various combinations of CSS ...

Node.js and MongoDB integration for implementing like and dislike buttons

I have been struggling to create a system for liking and disliking posts in my project. The issue I am facing is with the communication between the server and client side. Here is the form I am using: https://i.sstatic.net/IBRAL.png When I click on the li ...

Incorporate the ajax response into the design of the Material Design

I am looking to create a website that dynamically updates content using AJAX requests. I have JSON data that needs to be displayed in MDL cards. You can learn more about MDL cards here. Here is my AJAX code: $(document).ready(function(){ displayRecor ...

Utilizing Typescript to pass props to a material-ui button enclosed in styled-components

After setting up my react project using the typescript template, I decided to style the material-ui Button component using the 'styled' method from the styled-components library as shown below: import React from 'react'; import styled f ...

CSS Only Sidebar Dropdown (without using Bootstrap)

I want to create a sidebar with collapsible dropdown options and smooth animations using only pure css/js/html/jquery, without relying on bootstrap like I did in the past. Here is an example of what I created previously with bootstrap: Now, as a challenge ...

Unable to retrieve $wpdb, returning as null

In my development process, I am working on a basic plugin using the Wordpress Plugin Boilerplate. I have implemented AJAX to create an action triggered by a button press to remove an item from a custom database table I have set up. The AJAX function, butto ...

Exploring the power of the JavaScript this keyword

Can you explain the purpose of the line this.tasks = tasks; in relation to the constructor method? class TaskCollection { constructor(tasks =[]) { this.tasks = tasks; } } ...

Conceal a Component within an Embedded Frame

Hey there! I've been attempting to hide a header within an iframe, but it seems like my code isn't doing the trick. Could someone take a look and help me diagnose why the header is still visible? Thanks in advance! <iframe id="booking_iframe" ...

Building a static website with the help of Express and making use of a public directory

It seems that I am facing a misunderstanding on how to solve this issue, and despite my efforts in finding an answer, the problem persists. In one of my static sites, the file structure is as follows: --node_modules --index.html --server.js --app.js The ...

Oops! It looks like there was an error. Remember that AJAX events should be connected to the

I am completely new to the world of Ajax and unfortunately, I encountered an error message in my browser: "JQMIGRATE: AJAX events should be attached to document: ajaxComplete" After some research, it seems like I need to incorporate certain Ajax functi ...

Using AJAX with the GET method, send a form submission to retrieve a response using XMLHTTPRequest

I am working on a form where users can select values from two dropdown menus. The options in the dropdowns are populated dynamically from a JavaScript file, which contains a list of exchange rates. I have written the code to calculate and display the resul ...

Is there a way to insert a record upon the user clicking on the Add Record button?

// Here is my Component code // I want to figure out how to add a new row to the table with fresh values. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-uom', templateUrl: './uom.component.html ...

Tips for organizing the router.js file in VueJs

With my router.js file currently reaching around 500 lines, I’m looking for a better way to structure it. { path: "/", component: () => import("./../src/views/dashboard/Dashboard.vue"), meta: { auth ...