Steps for modifying the CSS style of a div element following an onclick event:

<html>
<head>
<style type="text/css">
.step_box {
    border: 1.0px solid rgb(204, 204, 204);
    border-radius: 10.0px 10.0px 10.0px 10.0px;
}
.step_box:hover{
background: rgb(184, 225, 252);
}
.selected {
    background-color : #fff000;
}
</style>
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $('.step_wrapper').on('click','.step_box',function () {
         $('.step_box').removeClass('selected');
         $(this).addClass('selected')
});
</script>
</head>
<body>
<div class="step_wrapper">
<div class="step_box" onclick="show('Page1');"> <span>Content of page 1</span></div>
<div class="step_box" onclick="show('Page2');"> <span>Content of page 2</span></div>
<div class="step_box" onclick="show('Page3');"> <span>Content of page 3</span></div>
</div>
</body>
</html>

At the moment, there are three child divs within a parent div. The step_box divs currently have a background color on hover. However, after clicking using the onclick method, I would like the step_box div to retain the background color with the ".selected" style. This will help highlight the div that the user selected.

Any suggestions on how to achieve this?

The code appears to work on this fiddle, but it doesn't function properly when loaded in my browser. Could it be an issue with how I linked jQuery to the HTML document?

If there are alternative methods or suggestions for accomplishing this task, I am open to hearing them. Thank you!

Answer №1

My updated version includes the addition of a .ready() function to your code.

<html>
    <head>
    <style type="text/css">
    .step_box {
        border: 1.0px solid rgb(204, 204, 204);
        border-radius: 10.0px 10.0px 10.0px 10.0px;
    }
    .step_box:hover,
    #selected_step_box,
    .QuickStartLong:hover {
        background: rgb(184, 225, 252);
    }
    .selected {
        background-color : #fff000;
    }
    </style>
    <script src="http://code.jquery.com/jquery-1.7.2.js"></script>
    <script type="text/javascript">
    $( document ).ready( function(){
        $('.step_wrapper').on('click','.step_box',function () {
             $('.step_box').removeClass('selected');
             $(this).addClass('selected')
        });
    });
    </script>
    </head>
    <body>
    <div class="step_wrapper">
    <div class="step_box" > <span>Content of page 1</span></div>
    <div class="step_box" > <span>Content of page 2</span></div>
    <div class="step_box" > <span>Content of page 3</span></div>
    </div>
    </body>
    </html>

For an alternative solution, check out version 2

css

.selected {
    background-color : #fff000;
}

js

$('.step_wrapper').on('click','.step_box',function () {
    $('.step_box').removeClass('selected');
    $(this).addClass('selected')
});

Take a look at this Fiddle:

.step_box:hover, #selected_step_box, .QuickStartLong:hover {
    background-color: rgb(184, 225, 252) !important;
}

To ensure your hover background color style is applied, use !important in your CSS.

Answer №2

Test it out

$('.section_container').on('click','.section_box',function () {
    $(this).parent().find('.section_box').css('background-color', '');
    $(this).css('background-color', '#f0f0f0');
});

Demo

Please note that this is simply an enhancement of the previous solution, as I may not fully comprehend your issue.

Answer №3

If you're looking to accomplish this task, AngularJS can be a valuable tool.

To make it work, simply include an ng-class in your div element with a class like "selected", and then define the behavior in your CSS. Here's an example:

<html ng-app="ExampleApp">
<head>
    <script src="scripts/angular.min.js"></script>
    <script type="text/javascript">
        (function() {
            var app = angular.module('ExampleApp', []);
            app.controller('ExampleController', function(){
                this.selected = 0; // or set it as 1 for the first item to be selected initially
                this.isSelected = function(value){
                    return this.selected === value;
                };
                this.setSelected = function(value){
                    this.selected=value;
                };
            });
        })();
    </script>
    <style type="text/css">
        .selected {
            color: #000;
        } 
    <style>
</head>
<body>
    <div ng-controller="ExampleController as examplectrl">
        <div ng-click="examplectrl.setSelected(1)" ng-class="{selected: examplectrl.isSelected(1)}" >
        <!-- Your content -->
        </div>
        <div ng-click="examplectrl.setSelected(2)" ng-class="{selected: examplectrl.isSelected(2)}" >
        <!-- Your content -->
        </div>
        <div ng-click="examplectrl.setSelected(3)" ng-class="{selected: examplectrl.isSelected(3)}" >
        <!-- Your content -->
        </div>
    </div>
</body>
</html>

Make sure to have the angular.min.js file included in your project files. I used generic classes in this example for easier understanding by the community.

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

Having difficulty toggling checkboxes within a grid using the select all feature

In order to toggle checkboxes for a specific column within a grid, I encountered an issue within the JS "onUPCSelectAll" function with the eval statement displaying the following error message: JS runtime error: Object doesn't support property or meth ...

Issue with Material UI React: Navbar does not properly align the box to the right side

https://i.sstatic.net/CHSwp.png I'm facing an issue with my navbar that is supposed to align all the page options to the right. Despite using a flexbox layout and trying different alignment properties like alignSelf: end, the text only moves slightly ...

If the text is too lengthy, enclose it within a div element

I am facing an issue with a fixed width DIV of 300px. Within this DIV, I have dynamic text that sometimes exceeds the width and gets cut off. Is there a way to make the text wrap when it exceeds the 300px limit without increasing the height of the DIV? Is ...

Capture data from Ajax requests and store them in PHP variables

When setting up a DDBB Insert using $.ajax, I encountered an issue. $(document).on('click','.submitMessage', function(){ content=$('textarea').val(); img=$('#messageImg').val(); stdMsg=$('.ms_stdMsg ...

Can AJAX Delete requests be executed without using jQuery?

Is it possible to use AJAX delete request without using jQuery? My JSON object at localhost:8000 appears like this: { "Students":[{"Name":"Kaushal","Roll_No":30,"Percentage":94.5}, {"Name":"Rohit","Roll_No":31,"Percentage":93.5}, {"Name":"Kumar ...

Tips for validating a form with the assistance of jQuery

While there are multiple answers out there for this particular question, I am specifically interested in validating an entire form with dynamic input fields sourced from a database similar to Google Forms. HTML <div class="rs_card"><spa ...

Using AJAX, JQuery, and PHP to convert a given name to match the columns in a query, utilizing the data sent

One thing that I'm wondering about is how PHP handles my ajax requests. For example, consider the following code snippet: $("#addUser").on('click', '.btnAddSubmitFormModal', function() { $.post("add.php", { ...

Multi-line auto-suggest list with typeahead functionality

Currently, I am utilizing typeahead with Twitter Bootstrap and AngularJS. The autocomplete suggestions are displayed in a single line, as seen in the screenshot below. However, I would like to have the big cities' names displayed on separate lines. Fo ...

Is it possible to display one division on top of another with a transparent opacity effect in HTML?

I'm struggling with designing web pages and currently working on a page on codepen.io using code from this link. <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1 ...

Looking for assistance with coding to show dates?

Seeking assistance with implementing an Ajax code to retrieve Google Calendar events and dynamically inserting two dates into the URL string fetched from Google Calendar. The initial date (timeMax=2021-02-28) should acquire the current date plus 30 days. ...

Pressing on an HTML element using JavaScript via the Selenium driver does not trigger the action

I'm attempting to use Selenium with Python to click on an element using JavaScript. Here's a snippet of my code: driver.execute_script("els=document.getElementsByClassName('buttons');\ for (var i = 0; i < els.length; i++) { ...

ngSanitize continues to present plain text rather than rendering HTML code

When working with AngularJS scope, I encountered the need to display certain items as HTML. After some research, I realized that integrating ngSanitize was necessary for this functionality. Here is how I implemented it in my app: <script src="Scripts/a ...

"Trouble with making jQuery AJAX calls on Internet Explorer versions 8 and 9

I've been searching for the answer to this problem without any luck. I have a page with jquery ajax calls to an API service. It works well in Chrome, Safari, Firefox, and IE 10, but fails in IE 9 and 8. Here is the code: $.ajax({ ...

Changing the background color of a PHP input based on the webpage being viewed - here's how!

I'm in the process of creating a website where each page will have its own unique background color. Additionally, I am using a PHP input for both the header and footer sections, which need to change their background colors based on the specific webpa ...

After AJAX has been loaded, Readmore.js fails to function properly

I am currently struggling to get the Readmore.js plugin working with AJAX content. The code snippet I have included is not cutting off the content inside the .more element as expected. <td><div class="more"><?php echo $row['book_desc&a ...

struggling to perfect the CSS styling

I am in need of a design similar to the image linked below: https://i.sstatic.net/Er1wT.png I attempted to create this layout using a table, but I have not been successful in aligning the side images properly. testTable.html <style> .container{ ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

"Utilizing AngularJS to asynchronously send an HTTP POST request and dynamically update

I've been working on an angularjs chat module and have come across a challenge. I developed an algorithm that handles creating new chats, with the following steps: Click on the 'New Chat' button A list of available people to chat with wil ...

Using table.column as a function in jQuery datatabbe is not supported

When using jquery datatable, I encountered an error stating "table.column is not a function." <script> $(document).ready(function() { var table = $('#lsotable').dataTable(); $("#lsotable thead th").each( function ( i ) { ...