Developing a variety of colored notification messages using JavaScript

I am working on creating a simple alert message with specific background colors depending on the user's login status. If a user fails to login, the alert message background-color should be red; if a user successfully logs in, the alert background-color should be green. I need help figuring out how to switch between using the 'alertsuccess' div and the 'alert' div based on the login outcome.

<div id="alert" style="display:none;">
<span class="closebtn" onclick="this.parentElement.style.display='none';">&  times;</span> 
<p id="alertmsg"> </p>
</div>

<div id="alertsuccess" style="display:none;">
 <span class="closebtn" onclick="this.parentElement.style.display='none';">&     times;</span> 
<p id="alertmsg"> </p>
</div>

 <input type="text" id="username" placeholder="Username" name="uname" maxlength="15" required>

<button id="button123" onclick="showalert('alert');">Submit</button>

Javascript Function:

 function showalert(id){
 var divelement = document.getElementById(id);
 var username = document.getElementById("username").value;

   if (username === ""){
    document.getElementById("alertmsg").innerHTML = "You didn't insert a username!";
    divelement.style.display =='none'
    divelement.style.display = 'block';
    }

    else if(username === "u1460714"){
    document.getElementById("alertmsg").innerHTML = "Successfully logged   in";
    divelement.style.display =='none'
    divelement.style.display = 'block';
    }
    }

CSS Styling:

#alert {
height:100px;
width:300px;
background-color: #f44336;
color: white;
position: fixed;
}

.closebtn {
margin-left: 15px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
}

.closebtn:hover {
color: black;
}

#alertmsg{
font-family:sans-serif;
font-size:15px;
text-align: center;
}

#alertsuccess {
background-color: #4CAF50;
}

Answer №1

One way to dynamically change the appearance of a div based on user input is by utilizing CSS classes. Instead of creating additional div elements, you can modify the existing div's appearance by toggling between different classes such as 'alert' and 'success'. The main alert div with the id 'alert' remains constant, allowing for easy styling changes through JavaScript.

Review the CSS styles applied to #alert, #alert.alert, and #alert.success to understand how the appearance changes based on the assigned classes. Remember that the default state of the 'alert' div is hidden, which can be overridden in your JavaScript code. It is also advisable to use classes instead of ids for better reusability of elements.

function showalert(id) {
  var divelement = document.getElementById('alert');
  var username = document.getElementById("username").value;
  if (username === "") {
    document.getElementById("alertmsg").innerHTML = "You didn't insert a username!";
    divelement.style.display = 'block';
    divelement.className = 'alert'
  } else if (username == "u1460714") {
    document.getElementById("alertmsg").innerHTML = "Successfully logged in";
    divelement.style.display = 'block'
    divelement.className = 'success'
  } 
}
#alert {
  height: 100px;
  width: 300px;
  color: white;
  position: fixed;
  display: none;
}

#alert.alert {
  background-color: #f44336;
}

#alert.success {
  background-color: #4CAF50;
}

.closebtn {
  margin-left: 15px;
  color: white;
  font-weight: bold;
  float: right;
  font-size: 22px;
  line-height: 20px;
  cursor: pointer;
  transition: 0.3s;
}

.closebtn:hover {
  color: black;
}

#alertmsg {
  font-family: sans-serif;
  font-size: 15px;
  text-align: center;
}
<div id="alert">
  <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
  <p id="alertmsg"> </p>
</div>

<input type="text" id="username" placeholder="Username" name="uname" maxlength="15" required>

<button id="button123" onclick="showalert('alert');">Submit</button>

Answer №2

Opting for a single div with the desired color setting can prevent duplication of IDs and potential issues.

function showalert(alert) {
  var alertBlock = document.getElementById(alert);
  var inputName = document.getElementById('username');
  var messageBlock = document.getElementById('alertmsg');
  alertBlock.style.display = 'block';
  if (inputName.value == '') {
    alertBlock.style.backgroundColor = 'red';
    messageBlock.innerHTML = 'No username entered';
  } else if (inputName.value == 'u2345') {
    alertBlock.style.backgroundColor = 'green';
    messageBlock.innerHTML = 'You entered the specific username';
  }
}
#alert {
  width: 200px;
  height: 200px;
  display: none;
 }
<div id="alert">
<span class="closebtn" onclick="this.parentElement.style.display='none';">X</span> 
<p id="alertmsg">test</p>
</div>

 <input type="text" id="username" placeholder="Username"name="uname" maxlength="15" required>

<button id="button123"onclick="showalert('alert');">Submit</button>

Answer №3

It appears there is a small error in your code snippet

divelement.style.display = 'none';

The correct syntax should have an equals sign instead of a double equal sign to assign the value. There may be other similar lines that need adjusting as well. I hope this clarification helps

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 make a drop down menu list appear when I click on the parent li, and then show the sub li using JavaScript?

I have a code that includes an image, HTML, and CSS code. Can anyone please tell me how I can set up a drop-down menu list to open the sub <li> elements when I click on a parent <li> using JavaScript? You can see the appearance of the code in t ...

Guide to resolving the issue of DELETE error 404 not found in express.js

I enrolled in a MEAN Stack course and have been making progress. I can easily add new data and fetch existing data, but running into trouble when attempting to DELETE data. The error message reads as follows: "DELETE http://localhost:3200/posts/5e831685bf7 ...

"Enhance user experience with jQuery's text expansion and collapse

Figuring out how to collapse and expand text with a button click has been challenging for me. I managed to make the text collapse when the button is clicked, but now I also need it to expand back again. The goal is to have the text initially hidden, then e ...

AngularJS's $resource module returns an empty array as a response

I am trying to display a table with items from JSON data. I have created a Service that returns the JSON data. In my controller, I am querying the Service to receive an array of data. It's a little confusing because I am putting the response in a new ...

Understanding how to retrieve the value count by comparing strings in JavaScript

In my array object, I am comparing each string and incrementing the value if one letter does not match. If three characters match with the string, then I increase the count value; otherwise, it remains 0. var obj = ["race", "sack", &qu ...

Mastering Polymorphism and Dependency Injection in AngularJS: Tips and Tricks for Success

This question revolves around design patterns. Rather than seeking a solution for achieving polymorphism in a service, I am interested in exploring the most widely accepted approach. Imagine there is a service named getData which retrieves data from vario ...

alter the color of the accordion display

Good day everyone, I am seeking help with a Bootstrap query. Here is the HTML code I am working on <!DOCTYPE html> <html lang="nl-NL"> <body> <div class="container-md"> <br> <div c ...

Display HTML tags on an HTML page using TypeScript

In my angular application, I encountered an issue where I needed to call one component inside another component. Initially, I was able to achieve this by simply using the second component's selector in the HTML of the first component: html: <div&g ...

Clicking on multiple instances of the same Vue.js component (popover) results in displaying identical data

Attempting to display an AJAX response in a popover shown by clicking an icon (a custom Vue component) brings about a challenge. The issue arises when there are multiple instances of this component, dynamically rendered through the v-for directive within a ...

Utilizing jQuery to Embed ID into <li> Element from JSON

When pulling data from a JSON file, I follow this approach: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>JSON Sample</title> </head> <body> <div id="placeholder"></div> ...

Although PhoneGap resolution remains consistent, the outcomes may vary

I seem to be facing a similar issue as discussed in this post on Stack Overflow: Screen Resolution On A PhoneGap App My problem is that I have both an iPad and an Android tablet, both with a resolution of 1024 pixels across. However, while my screen displ ...

What is the process for adding my JSON data to a select dropdown list?

Looking to populate a selectlist in HTML with options retrieved from an API. Below is the HTML code : <div id="example" role="application"> <div class="demo-section k-header"> <select id="FeaturesSelec ...

How to disable annoying browser ad extensions using Javascript

Is there a way to prevent browser add-ons from injecting HTML code? My website built in angularjs is experiencing routing issues due to certain browser add-ons. The following HTML snippet is causing errors in my angularjs: <script async="" src="http:/ ...

Eliminating repeated keys from an array of objects

I'm dealing with an array of objects that looks like this let array = [ { sector: "adad" }, { sector: "adadasdsd" }, { sector: "sdsdsd" }, { origin: "sdfsf" }, { destination: "dfsfsdf" } ]; My goal is to trans ...

Tips for removing duplicate objects from an array

I am utilizing the underscore.js plugin in my code I experimented with it on jsfiddle var basket=[{ "basketitems":[{"items":[]}], "itemdetails":[{ "amountPledged": "100", "bActivity": "Handloom Wo ...

Breaking the Boundaries of Fuzzy Search with JavaScript

I am currently utilizing ListJS's plugin for fuzzy search. It can be found at the following link: In an attempt to enhance the plugin, I implemented my own method to filter by the first letter of the items in the list. This involved selecting from an ...

Transform an array into an object with assigned key names

How can we transform the following array: [2019,2020,2021] into the format: { 0: {year:2019}, 1: {year:2020}, 2: {year:2021} } ...

React Component is not functioning with the timer running

I am currently developing a basic timer app using React. Here is the code snippet I have so far: import React from "react" const timer = (props) => { let time = 25; let processStatus = props.timerProcessStatus; // set to true if(processSta ...

Avoid running multiple YouTube views simultaneously within an AngularJS application

Currently, I have an Angularjs application that displays a list of Youtube videos utilizing the videogular node module. An issue has arisen where users can play multiple Youtube videos simultaneously, leading to potential violations of Youtube's poli ...

Angular 7: Easily Mark All Fields as Touched in Template-Driven Forms

When working with template-driven forms in Angular 7, I encountered a challenge with marking all fields as touched when the user blurs out of the last required field. Currently, I am manually passing each field to mark it as touched, which is not ideal. I ...