What is the best way to create CSS rules that can be dynamically applied as classes using JavaScript?

I have been attempting to use the addClass function in JavaScript to add a class, but I am struggling to make it work. Is there a specific way to define a class that will be added to an element when clicked on? Here is what I have attempted:

var input = document.querySelector('.sb-input');
var image = document.querySelector('.sb-label img');
image.addEventListener('click', function() {
  if (classie.has(input, 'open'))
    classie.remove(input, 'open')
  else
    classie.add(input, 'open');
  console.log('I am back')
});
.search-bar {
  position: absolute;
  top: 30px;
  right: 60px;
  width: 300px;
  height: 40px;
  overflow: hidden;
}
.sb-label {
  position: absolute;
  right: 0px;
  display: block;
  width: 50px;
  height: 40px;
  background-color: #32ab32;
  text-align: center;
  z-index: 10;
  cursor: pointer;
}
.sb-label img {
  display: block;
  z-index: 30;
  cursor: pointer;
}
.sb-input {
  position: absolute;
  right: 0px;
  width: 50px;
  height: 40px;
  border: none;
  backface-visibility: hidden;
  transition: left 0.7s;
  z-index: 5;
}
.sb-input .open {
  z-index: 90;
}
.sb-input .open {
  width: 100%;
  transition: left 0.7s;
}
<div class="search-bar">
  <form>
    <label class="sb-label" id="sb-label">
      <img src="search-icon01.png" width="35px" height="35px">
    </label>
    <input type="search" class="sb-input" id="sb-input" placeholder="Enter Search Word">
  </form>
</div>

By adding a callback and checking my console, I received confirmation that the function was executed properly. Further, altering the code demonstrated success:

var input = document.querySelector('.sb-input');
var image = document.querySelector('.sb-label img');
image.addEventListener('click', function() {
  input.style.zIndex = 90;
  input.style.width = '100%';
  console.log('I did it')
});

Seemingly, the issue lies within my stylesheet. Can anyone assist me in rectifying this inconsistency?

Answer №1

Could you share where you found the classie from? Maybe we should stick to using classList, as classie sounds a bit too fancy for us humble developers:P

CODE SNIPPET

<!doctype html>
<html>

<head>
  <meta charset='utf-8'>
  <style>
    .search-bar {
      position: absolute;
      top: 30px;
      right: 60px;
      width: 300px;
      height: 40px;
      overflow: hidden;
    }
    .sb-label {
      position: absolute;
      right: 0px;
      display: block;
      width: 50px;
      height: 40px;
      background-color: #32ab32;
      text-align: center;
      z-index: 10;
      cursor: pointer;
    }
    .sb-label img {
      display: block;
      z-index: 30;
      cursor: pointer;
    }
    .sb-input {
      position: absolute;
      right: 0px;
      width: 50px;
      height: 40px;
      border: none;
      backface-visibility: hidden;
      transition: left 0.7s;
      z-index: 5;
    }
    .sb-input .open {
      z-index: 90;
    }
    .sb-input .open {
      width: 100%;
      transition: left 0.7s;
    }
  </style>
</head>

<body>
  <div class="search-bar">
    <form>
      <label class="sb-label" id="sb-label">
        <img src="search-icon01.png" width="35px" height="35px">
      </label>
      <input type="search" class="sb-input" id="sb-input" placeholder="Enter Search Word">
    </form>
  </div>
  <script>
    var input = document.querySelector('.sb-input');
    var image = document.querySelector('.sb-label img');
    image.addEventListener('click', function() {
      if (input.classList.contains('open')) {
        input.classList.remove('open');
      } else {
        input.classList.add('open');
        console.log('i am back')
      }

    });
    var input = document.querySelector('.sb-input');
    var image = document.querySelector('.sb-label img');
    image.addEventListener('click', function() {
      input.style.zIndex = 90;
      input.style.width = '100%';
      console.log('did i do it')
    });
  </script>
</body>

</html>

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

What is the best way to locate a document's array item in MongoDB (Mongoose) using its "_id" field?

Here is the schema I'm working with using NestJS and Mongoose: @Schema({ timestamps: true }) export class Listing { @Prop({ type: [{ bidderId: { type: Types.ObjectId, required: true, select: false, ref: User.name, index: true }, ...

Starting a tab just once

I have successfully created 4 static HTML pages that include: Home About Services Contact Each page contains a link that leads to another static page named myVideo.html, which plays a video about me in a new tab. The link is available on every page so ...

Error: Page not found - The requested URL localhost:8080/login could not be located

My first time trying to utilize ajax and json is resulting in a 404 error. The issue seems to be that /login cannot be found even though I have defined LoginServlet with the url pattern /login in web.xml. Here is the code from web.xml: <servlet> ...

Learn the steps to upload multiple images to Firebase realtime database with the help of Vuejs

I am currently facing an issue with uploading multiple images to a real-time Firebase database. I have successfully managed to upload one image, but I am unsure how to handle multiple images at once. This is the code snippet for uploading a single image: ...

Keep bootstrap content aligned to the left

I am working on creating a webpage using bulma/bootstrap and my goal is to have some text positioned on the left side of the screen. I want this text to be displayed in the red area and to stay fixed in place when I scroll down, similar to a side panel. ...

The menu item fails to respond to clicks when hovering over the header background image

I'm having an issue with the Menu Link not working. I can click on the menu item when it's placed inside the body, but when I try to place it over the background header image, it stops working. Any help would be greatly appreciated. <div clas ...

Displaying a div when a radio button is clicked in React

I am attempting to create a functionality where clicking on one radio button will display another div in React. As a beginner in React, I have tried implementing the code below but encountered issues with hiding and displaying the content based on user inp ...

The catch-all route handler is triggered following a response being sent by a designated route handler

Currently, I am facing a peculiar issue with the routing on my Express-based server while trying to implement authentication. Here's a snippet of code that highlights the problem: app.get('/', function (req, res) { console.log('thi ...

Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js. Check out this code snippet: export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): ...

Navigating a complex web: Djikstra algorithm applied to a multigraph

Encountering an issue while implementing Dijkstra's algorithm on a multigraph. The graph consists of nodes representing stops with information and connections to other stops (edges). However, the challenge arises when there are multiple bus options be ...

Grouping of check-boxes in sets of 3

I need to customize the display of my checkboxes by grouping them side by side. Instead of showing them in a list format, I want them to be displayed in groups. For example, when there are 7 checkboxes, I would like them to be split into two columns with ...

Pass a variety of data points to PHP using Ajax requests

I am facing a challenge with passing multiple parameters during Ajax calls. The code works perfectly when I only pass one parameter. Here is the code snippet for the Ajax call: $.ajax({ type: "POST", url: "dataCartas.php", ...

Ensure that breadcrumb links remain on a single line by using text truncation in Bootstrap 5

For creating breadcrumbs in Bootstrap 5, the documentation suggests the following code: <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="#">Home ...

Choosing a random JSON object using jQuery

My jQuery script is designed to display the content from a JSON file when the page loads... $.getJSON('b.json', function(data) { $('#dictionary').empty().hide(); $.each(data, function(entryIndex, entry) { var html ...

Angular select automatically saves the selected option when navigating between views

I would like the selected option in my dropdown menu to stay selected as I navigate through different views and then return back. Here is the view: <select ng-model="selectedSeason" class="form-control" ng-options="season as 'Season '+ seas ...

How to include a key-value pair to a JSON object within an array using JavaScript

I am looking to include the following functionality in the JSON data provided below: "Check if the key name default exists, and if it does, add another key within the same object => ("pin" : 91)." I have attempted to achieve this using the code snippet ...

Using AngularJS to access the properties of a header within a $http request

As I navigate through the github API's pagination documentation, I am attempting to retrieve event items and extract the Link header (as recommended) in order to construct the pagination. However, I am facing difficulty in understanding how to work wi ...

Catching exceptions with jQuery Ajax

I'm facing a tricky issue with an exception that seems to slip through my fingers: //myScript.js.coffee try $.ajax async: false type: "GET" url: index_url success: -> //Do something error: -> //Do something els ...

Adjusting the width of columns in a flex layout using Bootstrap 4

On mobile, I am attempting to rearrange some elements in a different order. Currently, this is what I have: https://i.stack.imgur.com/fY3PQ.png Below is the HTML code: <main> <div data-color="yellow"></div> <div class="wrapper"& ...

Steps for creating a link click animation with code are as follows:

How can I create a link click animation that triggers when the page is loaded? (function () { var index = 0; var boxes = $('.box1, .box2, .box3, .box4, .box5, .box6'); function start() { boxes.eq(index).addClass('animat ...