I have multiple divs, and I would like to give a style at one when I click on it. And delete the style of all others divs it when I click on one other div.
To add style, this works :
document.getElementById(i).classList.add('border-blue-400', 'border-b-2', 'border-l-4');
The answer has been removed, I dont know why but I did this :
let docs = document.querySelectorAll(':not([id^='+i+'])')
for(let doc of docs)
{
doc.classList.remove('border-blue-400');
}
and it works
thanks
To remove it, I tried this but it does not work :
document.querySelectorAll(':not([id^='+i+'])').classList.remove('border-blue-400');
You can add an event listener to each element using for example a class, when an element in the class is clicked, the function will go over every element in the class and remove the style you defined.
By passing the clicked element to the function, we can then use target.id to check if the element we are going over has the same ID as the element we clicked on, in which case we apply a different style.
document.querySelectorAll(".div").forEach(div => addEventListener("click", (element) => {
document.querySelectorAll('.div').forEach(div => {
if(div.id != element.target.id) {
div.style.border = "10px solid green";
}
else {
div.style.border = "10px solid black";
}
});
}));
.div {
height: 100px;
width: 100px;
border: 10px solid green;
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="div" id="1"></div>
<div class="div" id="2"></div>
<div class="div" id="3"></div>
</body>
</html>
Related
I'm a complete beginner.
I'm trying to implement two buttons that change colors (green to blue) with one click (and once the implementation is completed, integrating it to the actual website).
The buttons need to do the following:
Both the buttons are initially green. Once a button is clicked, it should change its color to blue.
And after that same button is clicked the second time, it should revert back to its original color which is green.
Only one button out of the two can be blue at a time. Which means as soon as the user clicks button-2 after clicking button-1, the button-1 should turn back to green, and button-2 to blue.
So far, I can implement the first and third ones, but not the middle one.
Here are the necessary codes for it:
$(document).ready(function () {
$('#btn1').click(function(){
$('.btn').css('background-color', 'green');
$(this).css('background-color', 'blue');
})
$('#btn2').click(function(){
$('.btn').css('background-color', 'green');
$(this).css('background-color', 'blue');
})
});
.btn {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/styles.css">
<title>Document</title>
</head>
<body>
<button id = "btn1" class = "btn">Button</button>
<button id = "btn2" class = "btn">Button</button>
<!--<button id = "btn3" class = "btn" onclick="changeColor()">Button</button>
<button id = "btn4" class = "btn" onclick="changeColor()">Button</button> -->
<script src="/jquery-3.6.1.min.js"></script>
<script src="/index.js"></script>
</body>
</html>
To do what you require you can toggle a class on the clicked element which sets its background to blue. At the same time this class will be removed from all other buttons.
The code can also be simplified by using a single event handler bound to all .btn elements, instead of separate ones for each id.
jQuery($ => {
let $btns = $('.btn').on('click', e => {
let $btn = $(e.target).toggleClass('clicked');
$btns.not($btn).removeClass('clicked');
});
});
.btn {
background-color: green;
}
.btn.clicked {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>
Rory's answer is probably the best, but I think this one is more easy to understand for a beginner (although less elegant):
$('.btn').click(function(){
if ($(this).hasClass('clicked')) {$(this).removeClass('clicked');}
else {$('.btn').removeClass('clicked'); $(this).addClass('clicked');}
});
.btn {
background-color: green;
}
.clicked {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>
Aim : to click box(x) and it opens pop-up(x);
This is my first javascript project, i've done loads of research but i'm still struggling.
The reason I'm using a getElementByClassList is because it returns an array. I would then take the array and get the corresponding pop-up box and change its display settings in css.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box1 boxes"></div>
<div>
<div class="box2 boxes"></div>
<div class="box3 boxes"></div>
</div>
<div class="popup1"></div>
<div class="popup2"></div>
<div class="popup3"></div>
<script>
const boxes = document.getElementsByClassName('boxes');
// i would like to add an eventlistener for each object in the array
//
</script>
</body>
</html>
document.addEventListener("DOMContentLoaded", () => { // wait till all the DOM is Loaded, since querying objects at this point they are not there yet.
const boxes = document.querySelectorAll(".boxes"); // or use getElementsBy...
boxes.forEach(box => { // we are adding a click event listener to each box
box.addEventListener('click', (e) => {
const boxNumber = e.target.className.match(/box(\d)/)[1]; // through a regex we get the box number of the className
const popup = document.querySelector(`.popup${boxNumber}`);
console.log(popup)
// do whatever you want with the popup, add a className or whatever to open it :)
});
});
});
.boxes {
height: 20px;
width: 50px;
background: red;
margin: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box1 boxes"></div>
<div>
<div class="box2 boxes"></div>
<div class="box3 boxes"></div>
</div>
<div class="popup1"></div>
<div class="popup2"></div>
<div class="popup3"></div>
<script>
const boxes = document.getElementsByClassName('boxes');
// i would like to add an eventlistener for each object in the array
//
</script>
</body>
</html>
The method getElementsByClassName() indicats that return an array of html objects, in case there exists elements with passed css class.
The first step you have to iterate trough the array object:
for (int index = 0; index < boxes.length; index++)
{
}
Within for loop access to each element and assign the eventent handle
boxes[index].addEventListnener('click', function()
{
});
Within the body of declared anonymous function add your code.
You can try :
const boxes = document.getElementsByClassName('boxes');
const popups = document.querySelectorAll(".popups");
boxes.forEach((box,index)=>box.addEventListener("click",()=>{
const popup = popups[index]; // This gets the popup based on the box index so you will have to setup the html so that the popup for box1 is the first then popup for box2 second etc.
// Add styles to popup to display it
// Example
popup.style.opacity = "1";
})
Visit the 'mdn docs' or 'youtube' to learn how the array methods like forEach work
When you write element.style = "..." in JavaScript in adds the style attribute to the element you add the style to. Is there a way to add a style without the style attribute, without any libraries?
If you can come up with a selector that targets the element, another option is to append a stylesheet that contains that selector:
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = 'div { color: blue; }';
<div>Some div</div>
It'd be more reliable if you're permitted to change the element in some way, like add a class or other attribute:
const div = document.querySelector('div');
const className = `_${('' + Math.random()).slice(2)}`;
div.classList.add(className);
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = `.${className} { color: blue; }`;
<div>Some div</div>
With JS, you can write anything to the DOM, including a <style> tag. So for example:
const el = document.getElementById('changeColor');
el.onclick = function(e) {
const s = document.createElement('style');
s.innerHTML = '.box { background-color: yellow; }';
document.querySelector('body').appendChild(s);
}
.box {
width: 150px;
height: 150px;
background-color: red;
color: white;
padding: 20px;
}
#changeColor {
margin: 10px 0;
}
<body>
<button type="button" id="changeColor">Change It</button>
<div class="box">This is a box</div>
</body>
Add a CSS class inside styles tags
Use the DOMContentLoaded event to add a class to the element when the document is loaded
Get the elment through its tag name
Use setAttribute method in vanillaJS to add the CSS class to your tag elment
In this way it could be more maintainable yoru code, because you change at css level and JS auntomaticly will put the value tanken from css class declared
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
<style>
.styles {
color: red;
}
</style>
</head>
<body>
<p>Hello there</p>
<script>
let paragraph = document.querySelector("p")
document.addEventListener("DOMContentLoaded", () => {
paragraph.setAttribute("class", "styles")
})
</script>
</body>
</html>
how i can create a javascript code to add class name to specific divs only
for Exapmle : i want to add a class_name to from div5 to the end of all divs ?
try this
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>Click the "Try it" button to add the "mystyle" class to the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
</script>
</body>
</html>
If you're looking to add a class name from one div to others, I would recommend using JQuery. This can be done like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function changeColor(){
$( document ).ready(function() {
$("div").addClass("work");
});
}
</script>
<style>
.work {
color: red
}
</style>
<div style="width: 100%" class="work"><h1>Hello</h1></div>
<div style="width: 100%" class=""><h1>Hello</h1></div>
<button onclick="changeColor()">Change second color by inserting class!</button>
function applyClass(elem_position, tagname, classname)
{
var div_elems = document.querySelectorAll(tagname);
for (var i = elem_position-1; i < div_elems.length;i++)
{
div_elems[i].className=classname;
}
}
Usage
Applies class some_class to div elements starting from position 3
applyClass(3,'div','some_class');
Following is the html-javascript code for setting the background image and background image.
<html>
<link rel="stylesheet" type="text/css" href="try2.css">
<body>
Choose the color<br>
<div class="foo" id="#13b4ff" style="background-color:#13b4ff;"></div>
<div class="foo" id="ab3fdd" style="background-color:#ab3fdd;"></div>
<div class="foo" id="ae163e" style="background-color:#ae163e;"></div>
<br><br>
<div id="myframe1" style="padding:5px;width:300px;height:400px;border:1px solid black;">
<p><img src="img-thing.png" style="width:200px;height:200px;"/><p>
</div>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$('.foo').click(function(){
var str1 = $(this).attr('id');
var myframe = document.getElementById('myframe1');
myframe.style.backgroundColor=str1;
myframe.style.width=300;
myframe.style.height=400;
});
});
</script>
<div><input type='file' onchange="readURL(this);" />
<img id="blah"/></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#myframe1').css({
'background':'url('+e.target.result +')',
'background-size':'310px 410px'
});
};
reader.readAsDataURL(input.files[0]);//To display images uncomment this
}
}
</script>
</body>
</html>
The CSS FILE FOR COLORS IS(just in case you need to look at that as well)
.foo {
float: left;
width: 20px;
height: 20px;
margin: 5px 5px 5px 5px;
border-width: 1px;
border-style: solid;
border-color: rgba(0,0,0,.2);
}
Now the problem is:
I want that user may click upload image option first and upload the image as a background. But once that is done it not allowing user to se color as a background. How to fix that? On the contrary if color is choosen and then image, image can override as background.I want that both must be able to override each other. For convenience I also the fiddle link : here Also one more issue in the fiddle, other colors are not showing up, but they are working in my html file.
First of all correct your id name of class foo . use # in all ids ok
next empty the background of the div while on clicking of color div by
myframe.style.background="";
: Here is your corrected working code now
I think you can achieve by adopting two DIVs, one of them is used to render background images and the other render background color.
By changing 'z-index' of DIV, you can display COLOR at top or bottom.
Hope this can help you .
The following code should work under mainstream browser.
Take a try.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>
<style>
#DivBgColor,#DivBgImage{
position:absolute;
left:100px;
top:100px;
width:300px;
height:300px;
}
#DivBgColor{background-color:red;z-index:2}
#DivBgImage{background-image: url(https://s.yimg.com/rz/l/yahoo_en-US_f_p_142x37.png);background-repeat: no-repeat;z-index:4}
</style>
<script language=javascript>
function makeColorAbove(){
var objColor = document.getElementById("DivBgColor");
var objImage = document.getElementById("DivBgImage");
objColor.style.zIndex=2;
objImage.style.zIndex=1;
}
function makeImageAbove(){
var objColor = document.getElementById("DivBgColor");
var objImage = document.getElementById("DivBgImage");
objColor.style.zIndex=1;
objImage.style.zIndex=2;
}
</script>
<body>
<div id="DivBgColor" ></div>
<div id="DivBgImage"></div>
<input type=button value="makeColorAbove" onclick="makeColorAbove()">
<input type=button value="makeImageAbove" onclick="makeImageAbove()">
</body>
</html>