How can I change the background color of my notification box to red if the count is not equal to zero?

When the count equals 0, I don't want any effect on the notification box. However, when the count is not equal to zero, I want the notification box to turn red. I tried implementing this, but it's not working as expected. By not working, I mean nothing happens. I even checked the CSS using inspect element, but there's no change there...

      <style>
          {% block style %}
        #notification_dropdown.notification { background: red; }
        {% endblock %}
          </style>
    <li class="dropdown">
                  <a href="#" class="dropdown-toggle notification-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class='glyphicon glyphicon-inbox' aria-hidden="true"></span>
<span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu" id='notification_dropdown'>

                  </ul>
                </li>
    <script>
        $(document).ready(function(){
          $(".notification-toggle").click(function(e){
            e.preventDefault();
            $.ajax({
              type: "POST",
              url: "{% url 'get_notifications_ajax' %}",
              data: {
                csrfmiddlewaretoken: "{{ csrf_token }}",
              },
             success: function(data){
                $("#notification_dropdown").html(' <li role="presentation" class="dropdown-header">Notifications</li>');
                var count = data.count
                console.log(count)
                if (count == 0) {
                      $("#notification_dropdown").removeClass('notification');
                  var url = '{% url "notifications_all" %}'
                  $("#notification_dropdown").append("<li><a href='" + url+ "'>View All Notifications</a></li>")
                } else {
                      $("#notification_dropdown").addClass('notification');
                  $(data.notifications).each(function(){
                    var link = this;
                    $("#notification_dropdown").append("<li>" + link + "</li>")
                  })
                }
                console.log(data.notifications);
              },
              error: function(rs, e) {
                console.log(rs);
                console.log(e);
              }
            })
          })
        })
        </script> 

I tried adding

$("#notification_dropdown").removeClass('notification');

and

$("#notification_dropdown").addClass('notification');
after the if and else statements.

After that, I also applied CSS...but it still doesn't seem to work. What could be the issue here?

Answer №1

Check out this simplified example to address your inquiry: HTML showcasing your element along with a button to trigger/test the JS code:

<ul class="dropdown-menu" role="menu" id='notification_dropdown'>
Notification text
</ul>

<a href="#" id="button">Button</a>

CSS styling:

#notification_dropdown{
  background-color: green;
}

#notification_dropdown.notification{
  background-color: red;
}

Here is the associated JavaScript code:

myButton = $("#button");

clickCount = 0;

myButton.click( function() {
  myQuery = $("#notification_dropdown");
  console.log( clickCount );

  if( clickCount == 0 )
  {
    myQuery.removeClass( "notification" );
  }
  else
  {
    myQuery.addClass( "notification" );
  }

  // Incrementing count for testing purposes
  clickCount++; 
});

Simply click multiple times on the Button to activate the click function, changing the clickCount (for testing). Storing the JQuery query in myQuery variable prevents redundant queries without clear purpose.

Give it a try on JSFiddle

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

Display results in a Web application using Google Apps Script

function doGet() { return HtmlService.createHtmlOutputFromFile("vi"); // var output = HtmlService.createHtmlOutput('<b>Hello, world!</b>'); } function doPost() { return HtmlService.createHtmlOutputFromFile("vi"); // var out ...

Update the CSS property according to the selected list item in the slider using Glider JS

Looking to dynamically change the background image in CSS based on the active slide value in Glider.js Here is the CSS: html { background-image: url("https://images.unsplash.com/photo-1496518908709-02b67989c265?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEy ...

Utilizing async/await as a module function: A comprehensive guide

Express Route: const express=require('express'); const router=express.Router(); const trackRepo=require('../model/track'); router.post('/live',function(req,res){ const time=1439832167; const list=trackRepo.getAlerts ...

An unexpected error occurred in NodeJS: It is not possible to adjust headers once they have been sent

Recently, I've been working on a nodejs project and encountered the error message "Can't set headers after they are sent" when trying to get a response from http://localhost:8080/api/user. Despite researching solutions on Stack Overflow, none of ...

Arranging Text and Images in HTML/CSS to Ensure Optimal Placement When the Window Size Changes

Hello fellow coders! I've recently started diving into the world of website development and I have a query regarding positioning elements and handling window resizing. Can anyone help me out? I'm trying to center an image, a message, and a passw ...

What could be causing the code to malfunction and prevent window.ethereum from working properly?

While attempting to develop a dApp, I have encountered an issue with the browser in Visual Studio Code not recognizing the Ethereum connection, despite having installed MetaMask on the active browser session. Here is a snippet of my code used to test the c ...

A JavaScript code snippet to format a phone number in the pattern xx-xxxxxx

Please help me create a JavaScript function that can determine if the text in a textbox is a number. If it's not a number, I would like the function to focus on the textbox and change the format to look like this (xx-xxxxxx) when numbers are typed in, ...

Boosting Your Theme - Eliminating Redundant Styles

Currently, I am facing more of a best practice issue rather than a coding one. I am in the process of creating a custom bootstrap theme inspired by https://github.com/HackerThemes/theme-kit. Although I have a functional theme that I am satisfied with, I am ...

Utilize a React function to incorporate an external link

Looking to create a link to Twitter using the href attribute but encountering errors with the atag. Is there an alternative method I could use? In essence, I want to have a picture on my homepage that, when clicked, redirects the user to Twitter. I' ...

The sort function in Reactjs does not trigger a re-render of the cards

After fetching data from a random profile API, I am trying to implement a feature where I can sort my profile cards by either age or last name with just a click of a button. Although I managed to get a sorted array displayed in the console log using the h ...

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...

Unable to select the Icon's element

Hello everyone, I'm relatively new to using selenium and I've come across an icon element that I'm having trouble clicking. Below are the details of my issue: I attempted using this relative xpath, but I am still encountering a NoSuchElemen ...

Leveraging an Array of Objects in JavaScript

Need help with my JavaScript code! I want to adjust the date in a Date object by adding specific days and then save it. Here is what I have so far: let orderIdDateCorrectionDict = [ { "orderId": "2020053100", "dayCorrection": -146 }, { "orderId" ...

Creating a bottom bar using React and Material UI

I'm currently working on implementing a footer that will be displayed on every page of my Next.js application. To style this, I am utilizing Material UI. The following component is responsible for defining the layout across all pages of the app: impo ...

strange occurrences of bootstrap.min.css.map popping up

While working on my e-commerce website using Node, Express, Mongoose, and Bootstrap, I encountered an unexpected issue related to "bootstrap.min.css.map". The error 'Cast to ObjectId failed for value "bootstrap.min.css.map" at path "_id" for model " ...

find the index of the array-like name attribute in HTML using jQuery

In my code snippet, there is a simple structure like this: <div class="question_wrapper"> <input type="text" class="textinput_questions new_question" name="new_question[1][]"> <input type="checkbox" class="radioinput" na ...

I am having difficulty centering the contents on the page horizontally

Struggling to achieve horizontal alignment, I suspect the floats are causing issues. Removing them disrupts the layout with left_wrap and right_wrap not staying next to each other. Check out this example on JSFiddle .main_wrap {width:100%;} .main_wrap_2 ...

Hiding rows in a Datatable

Assistance needed to conceal specific rows in the datatable, If the User opts for "Show All" from the dropdown menu, the entire datatable should be displayed, However, if the User chooses "Hide USA", I wish to hide the rows with the Country value set ...

Is there a way for my box to avoid reaching the bottom of the page?

Is there a way to prevent my box from reaching the bottom of the page? I am currently using Bootstrap 4 and have tried the spacing utilities, but they don't seem to be effective. https://i.sstatic.net/YRqb4.png Attached is a picture showing that the ...

What is the process for incorporating a no-refresh submission using a hyperlink instead of a button?

Below are a few links that will trigger actions to insert data into different databases once clicked: <a href="#">insert into database1</a> <a href="#">insert into database2</a> <a href="#">insert into database3</a> Th ...