Change div background color on click event - javascript

I am trying to change div color on click but it is not working:
<html>
<head>
<script>
function data(){
var MyDiv1 = document.getElementById('newdata').innerHTML;
alert(MyDiv1)
if(MyDiv1==1) {
document.getElementsById('newdata').style.backgroundColor = "green";
}
}
</script>
</head>
<body >
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1
</div>
Logout
</body>
</html>
Where am I wrong here?
Any help will be appreciated

<html>
<head>
</head>
<body >
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1
</div>
Logout
</body>
</html>
<script>
function data(){
document.getElementById('newdata').style.backgroundColor = "green";
}
</script>
http://jsfiddle.net/n2uk4br1/
1) Script at the end;
2) Element not Elements
3) Call the right div name
4) That alert and if don't have a purpose

There were a couple of problems with your attempt. The following snippet does what you want:
function data(){
var myDiv = document.getElementById('newdata');
var content = myDiv.innerHTML;
if (content.trim() === "1") {
myDiv.style.backgroundColor = "green";
}
}
<div id="newdata" style="background-color: red; width: 100px;height: 50px;">
1
</div>
Logout
Firstly, you must be careful to distinguish between your <div> element and its contents. I have put the two into separate variables. I have used .trim() to remove any leading and trailing spaces from the contents of the <div> and also used the strict comparison ===.

it should be newdata
document.getElementById('newdata').style.backgroundColor = "green";
so your function will be
function data(){
var MyDiv1 = document.getElementById('newdata').innerHTML;
alert(MyDiv1)
if(MyDiv1==1) {
document.getElementById('newdata').style.backgroundColor = "green";
}
}

Related

change properties of two divs with one onclick and querySelectorAll()

I have multiple elements that are seperatet in two divs. The first div contains a Text and the second div a color.
When I click on one element the text and color should change and if I click it again it should change back.
The problem is that no matter which one I click, its always the last one which changes.
The HTML part:
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
The JavaScript part:
<script type='text/javascript'>
var box1Temp = document.querySelectorAll(".box1");
var box2Temp = document.querySelectorAll(".box2");
for (var i = 0; i < box1Temp.length; i++) {
var box1 = box1Temp[i];
var box2 = box2Temp[i];
box2.onclick = box1.onclick = function() {
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
}
</script>
It works, when I use only one div.
Then I can use 'this', instead of the 'box1' variable, to addres the right element.
But if I replace 'box1' with 'this' its still the text div that changes.
(I know it's obvious that this is happening, but I'm lost)
With a few small tweaks, this can be written a lot more cleanly:
// Capture click event for parent container, .toggle-set
for (const ele of document.querySelectorAll(".toggle-set")) {
ele.addEventListener("click", function() {
// Grab text and color elements
const textToggle = ele.querySelector(".toggle-text");
const colorToggle = ele.querySelector(".toggle-color");
// Toggle text
// NOTE: This could use further refinement with regex or something similar to strip whitespace before comparison
textToggle.textContent = textToggle.textContent == "Text1" ? "Text2" : "Text1";
// Toggle css classes
colorToggle.classList.toggle("colorGreen");
colorToggle.classList.toggle("colorRed");
});
}
.colorGreen { background-color: green; }
.colorRed { background-color: red; }
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
Your code is so confused
You were right for the this option.
you can do with simple onclick function :
function change(el){
box1 = el.querySelector('.box1');
box2 = el.querySelector('.box2');
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
I think following code snippet would help you to get your desired result
let box1 = document.querySelectorAll(".box1");
let box2 = document.querySelectorAll(".box2");
box1.forEach((b1,i) => {
b1.addEventListener("click",(ev) => {
ev.target.classList.toggle("colorGreen");
ev.target.classList.toggle("colorRed");
console.log(box2[i]);
if(ev.target.classList.contains("colorGreen")){
box2[i].textContent = "Text1";
}else{
box2[i].textContent = "Text2"
}
})
})

move an element from a div to another div

Let's assume that I have this structure
<div class="firstDiv">
<div class="insideDiv"></div>
</div>
<div class="secondDiv"></div>
<div class="thirdDiv"></div>
How can I move the .insideDiv from the .firstDiv to the .thirdDiv but going through the .secondDiv ?
I need just a hint or an idea. Thank you!
In vanilla JS, it works like this:
var moveIt = function() {
var outerDiv = document.getElementsByClassName('insideDiv')[0].parentElement;
var innerDiv = document.getElementsByClassName('insideDiv')[0];
if (outerDiv.nextElementSibling != null) {
outerDiv.nextElementSibling.appendChild(outerDiv.removeChild(innerDiv));
}
}
.firstDiv {
background-color: yellow
}
.secondDiv {
background-color: lightblue
}
.thirdDiv {
background-color: lightpink
}
<div class="container">
<div class="firstDiv">first
<div class="insideDiv">inside div</div>
</div>
<div class="secondDiv">second</div>
<div class="thirdDiv">third</div>
</div>
<button type="button" onclick="moveIt()">Move it!</button>
OPTIONAL: wrap-around in else statement below, this needs a scope to operate in. (set by div-element of class 'container'), to be added to above if statement.
else { outerDiv.parentElement.firstElementChild.appendChild(outerDiv.removeChild(innerDiv));
}
You can see a working example here: codepen: move child-element to nextSibling
If you don't mind using jquery:
<div class="firstDiv">
<div class="insideDiv">InsideBaseball</div>
</div>
<div class="secondDiv">SecondBase</div>
<div class="thirdDiv">ThirdBase</div>
<button id="SwapButton"> Swap! </button>
<script>
document.getElementById("SwapButton").onclick = function () {
var content = $('.insideDiv').html();
var content2 = $('.thirdDiv').html();
$('.thirdDiv').replaceWith(content);
$('.insideDiv').replaceWith(content2);
};
</script>

Using array to change colours

hi I'm trying to use an array to change colors. I want to Make a function called ChangeColor(num) with an argument for numbers and Use the function to change the color of the box so when the button is clicked on, it calls on the function and sends the correct number so that "box.style.backgroundColor = arrName[num];" Heres what i got so far.
<!DOCTYPE html>
<html>
<head>
<style>
#box {
width:200px;
height:200px;
background-color:black;
}
</style>
</head>
<body>
<div id="group">
<button id="blue">Blue</button>
<button id="red">Red</button>
<button id="green">Green</button>
</div>
<div id="box"></div>
<script type="text/javascript">
var colors = ["blue","red","green"];
var blue = document.getElementById("blue");
var red = document.getElementById("red");
var green = document.getElementById("green");
var box = document.getElementById("box");
var numclicks = 0;
blue.addEventListener("click", function() {
if(numclicks == 0) {
box.style.backgroundColor = colors[0];
}
});
red.addEventListener("click", function() {
if(numclicks == 0) {
box.style.backgroundColor = colors[1];
}
});
green.addEventListener("click", function() {
if(numclicks == 0) {
box.style.backgroundColor = colors[2];
}
});
</script>
</body>
</html>
You can simply attach an event listener to the buttons within #group and set the background-color of the #box the id of the clicked button:
var box = document.querySelector('#box');
document
.querySelectorAll('#group button')
.forEach(function (el) {
el.addEventListener('click', function () {
box.style.backgroundColor = el.id;
});
});
#box {
width:200px;
height:200px;
background-color:black;
}
<div id="group">
<button id="blue">Blue</button>
<button id="red">Red</button>
<button id="green">Green</button>
</div>
<div id="box"></div>
standard function
const colors = ["blue","red","green"];
const defaultColor = "white"; // if you want for kill errors
function changeColor(num){
document.querySelector("#box").style.backgroundColor = colors[num]||defaultColor
}
then you can added onclick events to buttons like this
<div id="group">
<button onclick="changeColor(0)" id="blue">Blue</button>
<button onclick="changeColor(1)" id="red">Red</button>
<button onclick="changeColor(0)" id="green">Green</button>
</div>
or with attributes like (but keep buttons elements depend to same order of array colors names)
html
<div id="group">
<button number="0" id="blue">Blue</button>
<button number="1" id="red">Red</button>
<button number="2" id="green">Green</button>
</div>
javascript
document.querySelectorAll("#group button").forEach((button)=>{
button.addEventListener('click', function () {
changeColor(button.getAttr("number"));
});
});
The other solutions use practices that are currently considered better. Here is a solution that includes the unnecessary array.
function changeColor(num) {
var colors = ['blue', 'red', 'green'];
document.getElementById('box').style.backgroundColor = colors[num];
}
#box {
width: 200px;
height: 200px;
background-color: black;
}
<div id="group">
<button id="blue" onclick="changeColor(0)">Blue</button>
<button id="red" onclick="changeColor(1)">Red</button>
<button id="green" onclick="changeColor(2)">Green</button>
</div>
<div id="box"></div>

unable to change image in a div through javascript

Here is my code:
<!DOCTYPE html>
<html>
<body>
<script>
function light() {
if (document.getElementById("push").value == "OFF") {
document.getElementById("bulb").style.backgroundImage = url("1.png");
document.getElementByID("push").value = "ON";
}
else {
document.getElementById("bulb").style.backgroundImage = url("2.png");
document.getElementByID("push").value = "OFF";
}
}
</script>
<center>
<input type="button" id="push" onclick="light()" value="OFF" />
<div id="bulb" style="background-image:url(2.png);width:320px;height:420px">
</div>enter code here
</center>
</body>
</html>
This line:
document.getElementById("bulb").style.backgroundImage = url("1.png");
attempts to call a function called url and pass a string to it, and then assign the result of that to the backgroundImage property.
Instead, you want to assign a string to backgroundImage directly:
document.getElementById("bulb").style.backgroundImage = "url(1.png)";
// Note ------------------------------------------------^----^----^^
Example:
document.getElementById("bulb").style.backgroundImage = "url(https://lh3.googleusercontent.com/-qJYMzFfIels/AAAAAAAAAAI/AAAAAAAAAGM/16Ir8NxI3gE/photo.jpg?sz=32)";
<div id="bulb" style="width: 32px; height: 32px"></div>
That said, it would be better to define your styling and such in CSS and then associate those styles with elements using selectors, for instance via a class association:
CSS:
.class-saying-what-the-image-represents {
background-image: url(1.png);
}
JavaScript:
document.getElementById("bulb").classList.add("class-saying-what-the-image-represents");
Example:
document.getElementById("bulb").classList.add("class-saying-what-the-image-represents");
.class-saying-what-the-image-represents {
background-image: url(https://lh3.googleusercontent.com/-qJYMzFfIels/AAAAAAAAAAI/AAAAAAAAAGM/16Ir8NxI3gE/photo.jpg?sz=32);
}
<div id="bulb" style="width: 32px; height: 32px"></div>

jQuery/Javascript : How to prepend elements without going back to the top of last prepended element?

Whenever I click prepend, after all elements are prepended, the view of the chat area switches to the top of the chat area or the last prepended element. This is different from append, whereby after all elements are appended, the view of the chat area does not switch to the end of the chat area or last appended element but still stays at its previous position.
How do I make the prepend function act in the same way as append in the sense that the view of the chat area does not change similar to FB's load previous message function?
Here is a sample code that illustrates what I mean.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<style type="text/css">
.chatbox{
border:1px solid #2a6496;
height: 600px;
margin-top:50px;
}
.chatbox div{
height: 100%;
}
.rightP{
border-left: 1px solid #2a6496;
}
.rightP .contents{
border-bottom: 1px solid #2a6496;
height: 70%;
}
.rightP .send{
padding : 5% 5% 5% 5%;
height: 30%;
}
#response{
height: 200px;
overflow-y: scroll;
overflow-wrap: break-word;
}
</style>
<script>
function appendMessage()
{
var data = 'hello';
var message = document.createElement('p');
message.innerHTML = data;
console.log(message.innerHTML);
$('#response').append(message);
$('#response').append($('.load'));
}
function prependMessage()
{
for(var $i = 0;$i<10;$i++)
{
var data = 'hello'+$i;
var message = document.createElement('p');
message.innerHTML = data;
console.log(message.innerHTML);
$('#response').prepend(message);
$('#response').prepend($('.load2'));
}
}
</script>
<body>
<div class="container">
<div class="chatbox">
<div class="col-sm-8 rightP">
<div class="row contents">
<div class="row msg">
<div id="response" class="msg form-group">
<a onclick="return appendMessage()" class="load btn btn-default">Append</a>
<a onclick="return prependMessage()" class="load2 btn btn-default">Prepend</a>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
In HTML there should be return in your onlick:
<a onclick="return loadMessage();" class="load btn btn-default">Load More Msg</a>
In JS you need to add return false to your function loadMessage.
var loadMessage = function(){
var firstMessage = $messagesWrapper.find('> p:nth-child(2)');
$.ajax({
....
if(messages.length<10){
$('.load').hide();//hide the load button if remaining messages to load is <10
}
success: function(messages){
$.each(messages, function() {
prependMessage(this);
});
},
....
});
return false;
};
Try this:
<div id="response" class="msg form-group">
<a onclick="loadMessage(); return false;" class="load btn btn-default">Load More Msg</a>
</div>
If this doesn't work, try another way:
var loadMessage = function(){
e.preventDefault(); // preventing any scroll action
var firstMessage = $messagesWrapper.find('> p:nth-child(2)');
(...)
And
var prependMessage = function(data){
e.preventDefault(); // preventing any scroll action
var message = document.createElement('p');
(...)
If this doesn't work please provide the whole code so we can reproduce.

Categories

Resources