Toggle background color of same div - javascript

I am trying to toggle the background color of same div.
It does changes once (from blue to red) as expected.
But it is not able to toggle back to red and continue toggling between the 2 colors. I know I should use "==" in the first if-statement but when using "==" not even the first toggle works.
Any suggestions how to get the toggle to work repetitive?
function toggleFunction() {
var x = document.getElementById("box");
if (x.style.background == "blue") {
x.style.background = "red";
} else {
x.style.background = "blue";
}
}
.box {
background-color: blue;
width: 100px;
height: 100px;
margin: 30px 0px 0px 30px;
}
<div id="box" class="box" onclick="toggleFunction()"></div>

The simplest solution would to create a new class called red and toggle that using classList.toggle. The main advantage of this approach would be that you can toggle more CSS properties, if you use a class for toggling and this will also deduct the if-else comparison for you.
function toggleFunction() {
var x = document.getElementById("box");
x.classList.toggle("red");
}
.box {
background-color: blue;
width: 100px;
height: 100px;
margin: 30px 0px 0px 30px;
}
.red{
background-color: red;
}
<div id="box" class="box" onclick="toggleFunction()"></div>

$( ".box" ).each(function() {
$( this).click(function() {
$( this ).toggleClass( "red" );
});
});
.box {
background: blue;
width: 100px;
height: 100px;
margin: 30px 0px 0px 30px;
}
.box.red {
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box" class="box"></div>
<div id="box" class="box"></div>

Related

Why change the color inside the div does not work?

Div with the id is clicking, the div with class is not clicking. By clicking div I want to change the color. If the color input within the div class is not working, if it is out of div class it works normally. How do I fix this?
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
if (e.target.id) alert(this.id);
clickedDivId = this.id;
e.stopPropagation();
};
}
function BackgroundColor(){
var x = document.getElementsByClassName("backgroundcolor")[0].value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
#divid{
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
.divclass{
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
<div class="divclass">
<input type="color" class="backgroundcolor" onchange="BackgroundColor()">
</div>
<div id="divid"></div>
The click event is firing for both divs, but your handler only shows the alert if the clicked div has an id, which the first one doesn't have.
You are also using old APIs (getElementsByTagName and getElementsByCalssName) that should really not be used anymore and the solution is much simpler that what you've done:
let color = document.querySelector(".backgroundcolor"); // Get reference to color input
let targetDiv = document.getElementById("divid"); // Get reference to second div
// Set up click event handler on the document
document.addEventListener("click", function(evt){
// Check to see if event originated at a div
if(evt.target.nodeName === "DIV"){
alert("You clicked a div!"); // Act accordingly
}
});
// Set up change event on color input
color.addEventListener("change", function(evt){
// Set color of target div
targetDiv.style.backgroundColor = color.value;
});
#divid{
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
.divclass{
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
<div class="divclass">
<input type="color" class="backgroundcolor">
</div>
<div id="divid">
</div>
function BackgroundColor(){
var x = document.getElementById("backgroundcolor1").value;
document.getElementById("clickedDivId").style.backgroundColor = x;
}
#divid{
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
.divclass{
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
<div id="clickedDivId" class="divclass">
<input type="color" id="backgroundcolor1" onclick="BackgroundColor()">
</div>
<div id="divid"></div>
It is better to use ID. I guess this is what you want.
By keep changing the color the background will change as well.

with javascript onclick add classname to a div

I want to achieve with javascript something like when i clink on any of thumbnail (btn-1, btn-2 and btn-3) the specific class should be add to box div dynamically.
my code: JSFiddle
document.getElementById('btn-1').onclick = function() {
document.getElementById('box').className = 'bg-1';
}
#box {
background-color: darkgray;
width: 200px;
height: 200px;
}
.thumbnail {
width: 30px;
height: 30px;
border: 1px solid;
margin: 5px;
position: relative;
float: left;
}
#btn-1 {
background-color: red;
}
#btn-2 {
background-color: green;
}
#btn-3 {
background-color: blue;
}
.bg-1 {
background-color: red;
}
.bg-2 {
background-color: blue;
}
.bg-3 {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box"></div>
<div class="thumbnail" id="btn-1"></div>
<div class="thumbnail" id="btn-2"></div>
<div class="thumbnail" id="btn-3"></div>
You javascript is working, but your CSS isn't.
You need to add !important as follows to .bg-1, .bg-2 and .bg-3
.bg-1 {
background-color: red !important;
}
Otherwise the id styling is taking preference over the class styling
You can see the classname is being added if you right click on the grey div and choose inspect element in Chrome.
Instead of bothering with classes, use simply a data- attribute like: data-bg="#f00"
$('[data-bg]').css('background', function () {
$(this).on('click', () => $('#box').css('background', this.dataset.bg));
return this.dataset.bg;
});
#box {
background: darkgray;
width: 120px; height: 120px;
}
[data-bg] {
width: 30px; height: 30px;
margin: 5px;
float: left;
}
<div id="box"></div>
<div data-bg="red"></div>
<div data-bg="#00f"></div>
<div data-bg="rgb(255,0,180)"></div>
<div data-bg="linear-gradient(to right, #E100FF, #7F00FF)"></div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
You want to use jquery .addClass() function:
$('.myButton').addClass('myNewClass');
The function would probably look something like this:
$(function () {
$('.thumbnail').click(function() {
$('#box').addClass($(this).attr('id'));
});
})
You can get all the thumbnails as an array, and then iterate through the array and dynamically add an event listener to each, which will add the desired className to box when clicked:
var thumbnails = document.getElementsByClassName('thumbnail');
Array.from(thumbnails).forEach(function(thumbnail) {
var id = thumbnail.id;
thumbnail.addEventListener('click', function() {
document.getElementById('box').className = id.replace('btn', 'bg')
});
});

Dynamic Mouse hover images using php and javascript

The hover event on an image should show it on a fixed div. How can i achieve this ?
For example : In flipkart if there is particular product and they give color variation for that product, when we hover on color variation we can see that color product.
If their is blue color option available for bag, we hover on blue box and then blue bag image appears.
Try this:
Save the url of img in Javascript
Add a data-color attribute to the elements
Use hover event
$("div.color").hover(function() {
var color = $(this).attr("data-col");
if (color == "blue"){
$("#box").html("<img src = 'https://rukminim1.flixcart.com/image/312/312/dress/a/p/h/fk01-1-elevate-women-m-original-imaehfswyyqct7jg.jpeg?q=70'/>");
}
if (color == "red"){
$("#box").html("<img src = 'https://rukminim1.flixcart.com/image/832/832/sari/p/e/q/1-1-vf-109-varni-retail-free-original-imaem8ypw2dhyekc.jpeg?q=70'/>");
}
if (color == "green"){
$("#box").html("<img src = 'https://rukminim1.flixcart.com/image/832/832/lehenga-choli/a/p/t/1-1-yue7984-sareeshop-free-original-imae96y2v3wdz5nr.jpeg?q=70'/>");
}
if (color == "yellow"){
$("#box").html("<img src = 'https://rukminim1.flixcart.com/image/832/832/sari/y/u/d/1-1-enix20-digitalmella-original-imaeaz7cehby8kqz.jpeg?q=70'/>");
}
});
.color {
heigth: 50px;
width: 50px;
border: solid 1px black;
display: inline-block;
}
#box {
height:300px;
width:300px;
border: solid 1px black;
margin-top:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class= "color" data-col="blue">blue</div>
<div class= "color" data-col="red">red</div>
<div class= "color" data-col="green">green</div>
<div class= "color" data-col="yellow">yellow</div>
<div id="box"><img src = "https://rukminim1.flixcart.com/image/312/312/dress/a/p/h/fk01-1-elevate-women-m-original-imaehfswyyqct7jg.jpeg?q=70"/></div>
BASIC CSS
.clearfix:after {
content: ".";
display: block;
width: 100%;
height: 0px;
visibility: hidden;
clear: both;
}
#prod-image-container {
border: 1px solid #CCC;
width: 600px;
height: 400px;
}
#prod-images {
list-style: none;
margin: 0;
padding: 0;
}
#prod-images li {
display: block;
float: left;
width: 50px;
height: 50px;
border: 1px solid #CCC;
margin: 0 4px 4px 0;
}
HTML
<ul id="prod-images" class="clearfix">
<li class="prod-color" data-big-image="https://dummyimage.com/600x400/CC0000/fff.png" data-color="#CC0000" /></li>
<li class="prod-color" data-big-image="https://dummyimage.com/600x400/CCC/fff.png" data-color="#CCCCCC"/></li>
<li class="prod-color" data-big-image="https://dummyimage.com/600x400/FFF000/fff.png" data-color="#FFF000"/></li>
</ul>
<div id="prod-image-container">
<img src="https://dummyimage.com/600x400/CC0000/fff.png" />
</div>
Using jQuery
<script>
$(function() {
$("#prod-images .prod-color").each(function( index ) {
var color_palette = $(this).attr("data-color");
$(this).css("background-color", color_palette)
});
$("#prod-images .prod-color").hover(function() {
var prod_image = $(this).attr("data-big-image");
$("#prod-image-container img").attr("src", prod_image);
});
});
</script>
Quick little fiddle: https://jsfiddle.net/adrianopolis/ast16g7t/

Add class to matching element without other specific class

Whenever a user clicks on the body I would like to add a class to a certain element, as long as that element doesn't have a specific class. The issue is, I re-use this element and some of these elements will have that specific class I mentioned and other will not. If one element has this class, with my current code, no element will have new class added.
Here is a fiddle showing the behaviour.
Example:
$('body').on('click', function(){
if ($('.box').hasClass('red') && !$('.box').hasClass('stay-red')) {
$('.box').addClass('blue');
}
});
html, body {
background: lightblue;
height: 100%;
}
.box {
height: 20px;
width: 20px;
margin-bottom: 10px;
}
.red {
background: red;
}
.blue {
background: blue;
}
<div class="box red stay-red"></div>
<div class="box red"></div>
It will be a lot easier with filter, and will avoid your problem:
$('body').on('click', function(){
$('.box').filter('.red:not(.stay-red)').addClass('blue');
});
html, body {
background: lightblue;
height: 100%;
}
.box {
height: 20px;
width: 20px;
margin-bottom: 10px;
}
.red {
background: red;
}
.blue {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div class="box red stay-red"></div>
<div class="box red"></div>
</body>
</html>
$('.box.red:not(.stay-red)').addClass('blue');
Is that what you want?
:not() Selector https://api.jquery.com/not-selector/
https://jsfiddle.net/7L3ub1sp/
$(function(){
$('body').on('click', function(){
$('.box').each(function(){
if ($(this).hasClass('red') && !$(this).hasClass('stay-red')) {
$(this).addClass('blue');
}
})
});
})
html, body {
background: lightblue;
height: 100%;
}
.box {
height: 20px;
width: 20px;
margin-bottom: 10px;
}
.red {
background: red;
}
.blue {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div class="box red stay-red"></div>
<div class="box red"></div>
</body>
</html>
You can use:
$('body').on('click', function(){
$('.box.red:not(.stay-red)').addClass('blue');
});
Or loop through all of them with each:
$('body').on('click', function(){
$('.box').each(function() {
if ($(this).hasClass('red') && !$(this).hasClass('stay-red')) {
$(this).addClass('blue');
}
});
});
If you want to avoid adding the new class to all elements if one of them has the other class, you can use some (or every):
var els = document.getElementsByClassName('box');
if(![].some.call(els, function(el) {
return el.classList.contains('stay-red');
}) [].forEach.call(els, function(el) {
return el.classList.add('blue');
});
Here is the body onclick you need:
$('body').on('click', function(){
$('.box.red:not(.stay-red)').removeClass('red').addClass('blue');
});
You also need to remove the class .red, even if in this precise case it works because the class .blue is defined after the class .red in the CSS

How to remove hover state when the element moves

I have this example:
<div class="container">
<div class="bp"></div>
</div>
http://jsfiddle.net/VKwjD/20/
if you hover the same square, his color changes; if you click, the parent size changes so the square move.
My problem is: If you don't move your mouse after the click, the square stays in the hover state... Why ?
It's possible to remove this state after the click? without moving the mouse...
Thank you for your help
HTML:
<div class="container">
<div class="bp" id="bp"></div>
</div>
CSS:
.container {
background: #FF0000;
width: 200px;
height: 200px;
position: relative;
}
.container.hide {
width: 50px;
}
.bp {
background: #00FFFF;
width: 30px;
height:30px;
top:0px;
right:0px;
position:absolute;
cursor: pointer;
}
.bp:hover{
background: #0000FF!important;
}
JavaScript:
$(document).ready(function() {
$('.bp').click(function() {
if($('.container').hasClass('hide')) {
$('.container').removeClass('hide');
var l1 = document.getElementById('bp');
l1.style.background = '#00FFFF';
}
else {
$('.container').addClass('hide');
var l1 = document.getElementById('bp');
l1.style.background = '#0000FF';
}
});
});

Categories

Resources