Guide to adding an active class to each block using Javascript

My website utilizes a Bootstrap layout consisting of a container, rows, and multiple "block-divs," each containing three separate divs. The number of block-divs is generated dynamically by a script based on user input.

The issue I am facing is that when a user clicks on a div, an active class is added to it. However, my current code only allows for one active class to be set for the entire page rather than individual blocks.

I am seeking a solution to assign an active class to each block without relying on any JavaScript frameworks, using pure JavaScript instead.

Here is an example of my layout: https://jsfiddle.net/9vr92ss4/

<!-- JavaScript code here -->
<!-- CSS code here -->
<!-- HTML code here -->

Answer №1

You have actively reassigning the class names using this:

for (i = 0; i < myCol.length; i++) {
  myCol[i].className = 'col-xs-4 myCol';
}

It is important to verify if the parent node of myCol matches the parent node of target:

function setActive(e) {
  var target = getTarget(e),
      section = target.parentNode;

  for (i = 0; i < myCol.length; i++) {
    if (myCol[i].parentNode === section) {
      myCol[i].className = 'col-xs-4 myCol';
    }
  }

  target.className = 'col-xs-4 myCol active';
}

Here's an updated snippet showcasing the working version:

var myCol = document.getElementsByClassName('myCol');

function getTarget(e) {
  if (!e) {
    e = window.event;
  }
  return e.target || e.srcElement;
}

function setActive(e) {
var target = getTarget(e),
      section = target.parentNode;
  
  for (i = 0; i < myCol.length; i++) {
    if (myCol[i].parentNode === section) {
      myCol[i].className = 'col-xs-4 myCol';
    }
  }
  
  target.className = 'col-xs-4 myCol active';
}

for (j = 0; j < myCol.length; j++) {
  myCol[j].addEventListener('click', function(e) {
    setActive(e);
  }, false);
}
/* Latest compiled and minified CSS included as External Resource*/

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet');

body {
    margin: 10px;
}

.myCol {
  padding: 40px 0;
  border: 1px solid #F44336;
  cursor: pointer;
  margin: 30px 0;
}

.active {
  background: #9C27B0;
  border: 1px solid #9C27B0;
  color:#fff;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container text-center">
  <div class="row">
  
    <div class="col-xs-12 block">
      <div class="col-xs-4 myCol">a-1</div>
      <div class="col-xs-4 myCol">b-1</div>
      <div class="col-xs-4 myCol">c-1</div>
    </div>
    
    <div class="col-xs-12 block">
      <div class="col-xs-4 myCol">a-2</div>
      <div class="col-xs-4 myCol">b-2</div>
      <div class="col-xs-4 myCol">c-2</div>
    </div>
    
    <div class="col-xs-12 block">
      <div class="col-xs-4 myCol">a-3</div>
      <div class="col-xs-4 myCol">b-3</div>
      <div class="col-xs-4 myCol">c-3</div>
    </div>
    
  </div>
</div>

Answer №2

Here is a more streamlined approach, utilizing the power of jQuery.

$('.myCol').click(function() {
  $(this).parent().find('.myCol').removeClass('active');
  $(this).toggleClass('active');
})
body {
  margin: 10px;
}

.myCol {
  padding: 40px 0;
  border: 1px solid #F44336;
  cursor: pointer;
  margin: 30px 0;
}

.active {
  background: #9C27B0;
  border: 1px solid #9C27B0;
  color: #fff;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="container text-center">
  <div class="row">

    <div class="col-xs-12 block">
      <div class="col-xs-4 myCol">a-1</div>
      <div class="col-xs-4 myCol">b-1</div>
      <div class="col-xs-4 myCol">c-1</div>
    </div>

    <div class="col-xs-12 block">
      <div class="col-xs-4 myCol">a-2</div>
      <div class="col-xs-4 myCol">b-2</div>
      <div class="col-xs-4 myCol">c-2</div>
    </div>

    <div class="col-xs-12 block">
      <div class="col-xs-4 myCol">a-3</div>
      <div class="col-xs-4 myCol">b-3</div>
      <div class="col-xs-4 myCol">c-3</div>
    </div>

  </div>
</div>

Answer №3

Approach the problem by considering each row individually to make it easier.

Your progress is commendable. To streamline your process, utilize a data structure to keep track of your grid's status.

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

Querying MySQL database for variable values in JavaScript

I have a JavaScript file on my website that carries out calculations. Currently, my variables are defined as global variables in another JavaScript file. What I would like to do is make these variables dynamic by pulling their values from a MySQL database ...

Concerning the issue of components not loading correctly when using Angular with Lazy Loading Routing

Encountering an unusual issue while utilizing lazyload routing in our application! Within AppModule, there is TopModule followed by DashboardModule, all being loaded lazily. When localhost:4200/dashboard is accessed, the loading sequence is AppModule, To ...

Is it feasible to use both position absolute and position sticky at the same time? If so, how can this be accomplished?

Is there a way to keep an element fixed on the display without using position: fixed? I want the element to always remain above other elements, so I used z-index. Additionally, I would like the element to be able to move horizontally without scrolling acro ...

How to center elements vertically in a navbar using Bootstrap 5

I am currently utilizing bootstrap to design a navbar featuring various links. One of these links is a button, which is causing alignment issues with the rest of the links. body{ background: rgb(27, 25, 25); } .btn{ border-radius: 3em; } ...

"Enhance Your Website with jQuery UI Tooltips Featuring HTML Content

Is there a way to customize the appearance of tooltips using jQuery UI Tooltip? I want to format tooltips similar to the image shown below for HTML content. Example: JavaScript: $(function () { $.widget("ui.tooltip", $.ui.tooltip, { optio ...

What is the proper way to incorporate a backend variable within an EJS script block?

<!-- begin snippet: js hide: false console: true babel: false --> <script> // initializing the map var map = L.map('map').setView([25.037393872113785, 121.56372070312499], 12); // loading a tile layer var baseLayer = L ...

The meteorite experienced a crash as startup.js attempted to connect with Mongo

Setting up a Mongo database for a meteor project has been tricky for me. I've created a startup.js file to load the necessary files, but as soon as I start meteor, it crashes. Can anyone lend a hand, please? Here is a snippet from the HTML file: < ...

Assign Multiple Values to a PHP Variable and populate an HTML input field with the value

This is the input field I am currently using. https://i.sstatic.net/0hv1q.jpg Here is how I am displaying/printing my variable. https://i.sstatic.net/3Fptg.jpg I am encountering the following error: Array ( [0] => Notice: Array to string conve ...

Can I issue multiple SADD or ZADD commands in a single .sadd/.zadd call using ioredis?

I'm currently experimenting with ioredis for caching and indexing a substantial volume of data. However, my searches haven't yet yielded information on whether it supports performing multiple SADDs in one call. Can this be done, and if so, are t ...

The same size background effect

I am looking to create a list of names that are all the same size. How can I achieve this using Bootstrap? <ul class="list-unstyled"> <li> <a class="btn btn-xs btn-warning"> <span >Loren ipsum</span> </a> ...

Dynamically create an array of various objects

I have a task where I need to manage a list of users, each with a checkbox and an input field. My goal is to save all the data when there are changes made to the input field or checkbox: import React, { useState } from "react"; import "./sty ...

Should input fields be placed inside separate columns or share a column in Bootstrap to keep them together while being right justified?

When using Bootstrap, is it better to place separate input fields inside their own col or share a col to keep them together and right-justified? I have a combo and input that I want to display on the same row at the right-hand side of the screen. If I put ...

What could be the reason behind the failure of my JSON post method on the local web server for my JSON file?

Recently, I decided to dive into learning Javascript with the goal of creating a website that utilizes JSON files for storage. So far, I have managed to get the GET method to work: $.ajax({ type: 'GET', url: 'Projects/Sample/data.json&a ...

Could the issue at hand possibly stem from the fact that the router isn't fully operational? It appears that router.query

Having trouble retrieving the parameters from the URL using router.query. I've tried various approaches but keep getting an undefined result. It seems like I'm on the right track, though. Highlighted query param in yellow... https://i.stack.img ...

Using Ngmap to dynamically display markers using ng-repeat in JavaScript

In my project, I am utilizing the angularjs-google-maps directive for map functionality. Below is a snippet of code demonstrating how markers are added to the map: <map id="map" style="height:450px" zoom="4" zoom-to-include-markers='auto' ce ...

Deleting a row in a MySQL database using AJAX and PHP: A step-by

Is it possible to remove a record from a PHP MySQL database using AJAX? Consider the following code: delete_record.php <?php require_once "../include/connection.php"; if ($_REQUEST['rowid']) { $sql = "DELETE FROM lesson1 WH ...

Retrieving JSON information using Ajax to enhance Cytoscape visualization

Looking to share a network using Cytoscape web or, if possible, cytoscape.js. Due to the size of my data, I find it easier to export it from Cytoscape desktop and grab it using ajax in my HTML. Previously, before version 3.1.0 of Cytoscape, I could export ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Repeated triggering of add event detected in blueimp File Upload function

Currently, I am in the process of developing an upload module for my website project. After careful consideration, I have decided to go with the blueimp File Upload due to its extensive configuration options. The main concept is to have a button that trig ...

Customizing Background Colors with ChartJs and React

In my React project, I am looking to implement a Line chart styled as an Area Chart using the 'react-chartjs-2' library. Here is the desired outcome I aim to achieve, with a background fill below the line: https://i.sstatic.net/zOgzz.png Below ...