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

Set up webpack on your Mac using npm

Seeking help to install webpack using npm: sudo npm install -g webpack The following error message is encountered: node-pre-gyp WARN Using needle for node-pre-gyp https download node-pre-gyp WARN Pre-built binaries not installable for <a href="/cdn- ...

Using jQuery, you can store values in a PHP array or session by making an AJAX

Is there a way to store values in PHP array or PHP session using ajax in jQuery? I am trying to send some values via ajax to a PHP page and store them. The issue is that every time the array/session only returns the latest sent value, and not the previous ...

CSS styling not functioning properly

After spending a considerable amount of time on this issue... <div id="pager" style="top: 5px; position: relative; " class="pager" > <form> <img src="http://tablesorter.com/addons/pager/icons/first.png" alt="first" class="first" ...

What is the process for creating a Sass mixin that declares a selector at the base level, rather than nested within another

Apologies for the unconventional terminology in the query, but I am struggling to find better words to describe it. Hopefully, this example will clarify my intention: scss-syntax .my-smug-selector { @include my-smug-mixin(30px); } desired css-output ...

Leverage angular-translate to establish placeholder text upon blurring

Just starting out with Angular and facing the challenge of implementing localization in my project. I have a lot of input fields that need their placeholders translated. In my HTML, I'm trying to achieve this: <input type="email" placeholder="{{ & ...

Ensure that the form is validated even when setState is not executed immediately

I am currently working on a form in React and I am facing an issue with validation. When the Submit Form button is clicked without filling in the input fields, an error should be displayed. This part is functioning correctly. However, even when the fields ...

What is the best way to deliver hefty files to users? Utilize the node-telegram-bot-api

bot.sendDocument(id, 'test.zip'); I am facing an issue while trying to send a 1.5GB file using the code above. Instead of being delivered to the user, I receive the following error message: (Unhandled rejection Error: ETELEGRAM: 413 Request En ...

Despite using twitter bootstrap, the elements on my webpage are still overlapping one another

While implementing Twitter Bootstrap on my website, I encountered a problem where elements start overlapping if the window size is reduced. This issue does not look appealing, and I expected Twitter Bootstrap to ensure that my website is fully responsive a ...

Converting objects into JSON format

I'm trying to transform an object that looks like this: { user[id]: 1, user[name]: 'Lorem', money: '15.00' } Into the following structure: { user: { id: 1, name: 'Lorem', }, money: ...

How to send the value of a JavaScript loop variable to PHP using AJAX

How can I send variables in a loop to a PHP file using AJAX? var lat; var lng; var array = [22.399602, 114.041176, 22.344043, 114.0168, 22.327529, 114.087181]; console.log(array); for (var i = 0; i < 6; i += 2) { lat = array[i]; console.log("l ...

Avoiding multiple ajax requests due to multiple clicks

I have a blog on WordPress that has a jQuery code allowing users to click a bookmark link to save the post as a bookmark. Each post displays a total bookmark counter in this format: "Bookmarked (5)". The issue is that when a user clicks multiple times on t ...

Pattern for either one or two digits with an optional decimal point in regular expressions

Currently, I'm utilizing for input masking. I am specifically focusing on the "patterns" option and encountering difficulties while trying to create a regex expression for capturing 1 or 2 digits with an optional decimal place. Acceptable inputs: ...

What is the reason behind the significant 80% reduction in PNG files by grunt-contrib-imagemin compared to the minimal reduction of less than 0.1%

Just getting started with Grunt here. Recently, I've been experimenting with grunt-contrib-imagemin. When it comes to compressing PNG files, it does an impressive job. It typically reduces the size by around 80%. However, I'm finding that the ...

Tips for effectively passing an array to props in Vue when leveraging Typescript and the class component decorator

I'm currently struggling to understand the proper method of passing an array as a prop to a component in Vue, using Typescript and the class component library. Following the official template, I attempted the following approach: <script lang="ts"& ...

Hover function not functioning properly

I can't figure out why this hover effect isn't working, there doesn't seem to be a negative z-index or anything like that. At most, it just flashes on hover; .menu{ border-radius: 50%; width: 100px; height: 100px; background: white; box-sha ...

React does not always remove event listeners when using the useEffect hook's return callback

I have a functionality in my component where it initializes a key event listener. This event is supposed to trigger an API call to fetch random data. useEffect(() => { const keyUpEvent = (event) => { if (event.code === "Enter") { ...

What are the reasons behind the lack of smooth functionality in the Bootstrap 4 slider?

My customized bootstrap4 slider is functional, but lacks smoothness when clicking on the "next" and "prev" buttons. The slider transitions suddenly instead of smoothly. Any suggestions on how to fix this? Here is the code for the slider: $('.carous ...

Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can ...

Accessing information from Firebase and displaying it within an Angular Controller

As a newcomer to the latest Firebase SDK (with some experience using angularfire), I set out to retrieve data and display it using Angular. This is my progress so far: var app = angular.module('dApp',[]); app.controller('listingControler&a ...

Submitting PHP Ajax form automatically, no user input required

Is there anyone who can help me with this issue? I recently set up a PHP Ajax form on my website that is validated using jQuery. All fields must contain content for the form to be submitted successfully. However, I am encountering an unusual situation wh ...