Here is a little story... I want to make a for loop that makes make 's to addenventlisteners so when I move over :hover/onmouseover it should shift bewteen 2 colors. But I can not figure out how I get the keyword down to the function redB ...
But I dont know if I am on the rigth way...
$(document).ready(function() {
var i;
for (i = 0; i < 10; i++) {
document.getElementById("sek2" + i + ).addEventListener("mouseover", Over(this));
document.getElementById("sek2" + i + ).addEventListener("mouseout", Out(this));
}
});
function greyB(x) {
x.style.backgroundColor = "grey";
}
function redB(x) {
x.style.backgroundColor = "red";
}
Using vanilla javascript, close to your current code, this is as easy as:
var i;
for (i = 0; i < 1; i++) {
document.getElementById("sek2" + i).addEventListener("mouseover", function(){ greyB(this); });
document.getElementById("sek2" + i).addEventListener("mouseout", function(){ redB(this); });
}
function greyB(x) {
x.style.backgroundColor = "grey";
}
function redB(x) {
x.style.backgroundColor = "red";
}
<div id="sek20">Mouse over me</div>
If using jQuery this is even easier:
$("[id^='sek2']").on('mouseover', function(){
$(this).css('background-color','grey');
}).on('mouseout',function(){
$(this).css('background-color','red');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sek20">Mouse over me</div>
you are calling the wrong function name and if you use $(document).ready() you need ah jquery library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Js code
$(document).ready(function() {
var i;
for (i = 0; i < 10; i++) {
document.getElementById("sek2" + i + ).addEventListener("mouseover", greyB);
document.getElementById("sek2" + i + ).addEventListener("mouseout", redB);
}
});
function greyB() {
this.style.backgroundColor = "grey";
}
function redB() {
this.style.backgroundColor = "red";
}
Is something like this what you looking for?
$(document).ready(function() {
var i;
for (i = 0; i < 10; i++) {
let newDiv = document.createElement('div');
newDiv.classList.add('square');
newDiv.addEventListener("mouseover", greyB);
newDiv.addEventListener("mouseout", redB);
document.querySelector('body').appendChild(newDiv);
}
});
function greyB() {
this.style.backgroundColor = "grey";
}
function redB() {
this.style.backgroundColor = "red";
}
.square {
background-color: red;
width: 100px;
height: 100px;
margin: 10px;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I ended with this solution, but can anyone tell there to go getting more information about this code. What kind of language maybe a link to some place. So I not getting different code to play with futher.
Thanks...
var i;
for (i = 0; i < 1; i++) {
document.getElementById("sek2" + i).addEventListener("mouseover", function(){ greyB(this); });
document.getElementById("sek2" + i).addEventListener("mouseout", function(){ redB(this); });
}
function greyB(x) {
x.style.backgroundColor = "grey";
}
function redB(x) {
x.style.backgroundColor = "red";
}
<div id="sek20">Mouse over me</div>
Related
I have made 30 buttons in JavaScript now I want all buttons to be green like the first button and whenever you click on a button it turns and stays red.
For some reason only the first button is green and whenever I click it it won't turn red. I tried using: button.style.backgroundColor = "red"; in a function to make the button red when clicked but this doesn't work
const color = ["green"];
page();
function onbuttonclicked() {
document.body.style.backgroundColor = color[nr - 1];
}
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function createButtons(amount) {
for (var a = 1; a < (amount + 1); a++) {
var button = document.createElement("button");
button.style.backgroundColor = color[a - 1];
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
set_onclick(amount);
}
<div id="container"></div>
EDIT
thanks for all the answers it isnt possible to only change certain buttons when you click on them right? so when i click on button1 nothing happens but whenever i click on button 3 it turn red
You need to pass nr as a parameter in onbuttonclicked function
EDIT:
OP Comment:
okay so i need to add an parameter. but i want all 30 buttons to be green so when you open the page all buttons are green this also has to do with the parameter?
For that in your loop createButton, change color[a - 1] for color[0]
const color = ["green"];
function onbuttonclicked(nr) {
document.body.style.backgroundColor = color[nr - 1];
}
function page() {
//style page
document.body.style.backgroundColor = "grey";
createButtons(30);
}
function set_onclick(amount, nr) {
for (let a = 1; a < (amount + 1); a++) {
document.getElementById(`button${a}`).setAttribute("onclick", `onbuttonclicked(${nr})`);
}
}
function createButtons(amount) {
for (let a = 1; a < (amount + 1); a++) {
const button = document.createElement("button");
button.style.backgroundColor = color[0];
button.id = `button${a}`;
button.innerHTML = `button ${a}`;
container.appendChild(button);
}
set_onclick(amount, 1);
}
page();
<div id="container"></div>
const number_of_buttons = 30;
createButtons();
function createButtons(){
var container = document.getElementById("container");
for(var i=1;i<=number_of_buttons;i++){
var button = document.createElement("button");
button.innerText = "Button " + i;
button.style.backgroundColor = "green";
button.onclick = function(event){
var source = event.target || event.srcElementl
source.style.backgroundColor = "red";
};
container.appendChild(button);
}
}
button{
margin: 10px;
font-family: 'Consolas';
font-size: 20px;
padding: 5px;
outline: none;
cursor: pointer;
transition: 0.5s;
}
button:hover{
border: 1px solid black;
}
button:active{
transform: translateY(2px);
}
<div id="container">
</div>
This is what you have asked for!
I did the styling for better looks!
This line: button.style.backgroundColor = color[a - 1]; is wrong, since your color array only contains a single string ("green"). You should do color[0], or, you need to populate the array to have 30 elements.
document.body.style.backgroundColor = color[nr - 1]; - Where is this nr variable came from? The correct line should be button.style.backgroundColor = "red"; or - again - you can populate the color (i.e const color=["green", "red"]) and use color[1].
Check out this demo
A common way to do this is to use CSS classes:
page();
function onbuttonclicked(a) {
//document.body.style.backgroundColor = color[nr - 1];
document.getElementById("button" + a).classList.remove("button")
document.getElementById("button" + a).classList.add("clickedbutton")
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
function createButtons(amount){
for (var a = 1;a <(amount + 1); a++) {
var button = document.createElement("button");
button.classList.add("button")
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
set_onclick(amount);
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<div id="container"></div>
I'm working on a progress bar. It has a label. I want to adjust that label a certain script is finished. After finding some answers of probable solution, I came up with the following script. The first initiates and works as expected. However, the second one doesn't. What's wrong with it? Here's the code:
HTML:
<form method ="post">
<input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>
Javascript:
<script>
function move() {
var elem = document.getElementById("myBar");
var myFunc01 = function() {
var i = 1;
while (i < 101) {
(function(i) {
setTimeout(function() {
i++;
elem.style.width = i + '%';
elem.innerHTML = i + '%';
}, 600 * i)
})(i++)
}
};
myFunc01();
}
</script>
<script>
function finalize() {
var elem = document.getElementById("myBar");
var myFunc02 = function() {
elem.innerHTML = 'Finalizing...';
};
setTimeout(myFunc02, 600);
}
</script>
var elem = document.querySelector('#myBar');
function done() {
elem.innerText = 'UPLOAD HAS FINISHED';
}
var upload = function(callback) {
var width = 1;
var id;
var frame = function() {
if (width >= 100) {
clearInterval(id);
callback();
} else {
width++;
elem.style.width = width + '%';
}
};
id = setInterval(frame, 10);
};
/*
upload(function() {
elem.innerText = 'UPLOAD HAS FINISHED';
});
*/
#myProgress {
width: 100%;
background-color: grey;
}
#myBar {
width: 1%;
height: 30px;
background-color: green;
text-align: center;
line-height: 27px;
}
<button onclick="upload(done)">START UPLOAD</button>
<div id="myProgress">
<div id="myBar"></div>
</div>
You could use a callback. A callback is a function that runs upon completion.
function move(callback) {
//code you want to happen first
}
move(function(){
//code you want to have happen after completion
})
thats the basic idea of how a simple callback works
Thanks James, that's it!
After some re-arranging, this is what the second script looks like. And it works as expected.
<script>
function finalize() {setTimeout(function(){
var elem = document.getElementById("myBar");
var myFunc02 = function() {
elem.innerHTML = 'Finalizing...';
};
myFunc02();
}
, 600);}
</script>
I'm curious if there is a way to repeat a function for as long as user stays on the page. I want function f1() to repeat changing the color of div #gallery. It's probably an infinitive loop or something, please help me.
function f1() {
setTimeout(
function() {
document.getElementById("gallery").style.backgroundColor = "blue";
}, 3000);
setTimeout(
function() {
document.getElementById("gallery").style.backgroundColor = "red";
}, 6000);
}
#gallery {
width: 500px;
height: 300px;
background-color: red;
}
<body onload="f1()">
<div id="gallery">
</div>
</body>
The previous method of using setInterval is really great, but I personally like to have a little bit more control over what happens so I use something like this for repetition:
fiddle
The 'meat and bones' is a loop like this:
const target = document.getElementById('target');
const colors = ["red", "blue", "purple", "black", "gray", "aliceblue"];
const randomColor = () => {
const randomInt = Math.floor(Math.random() * colors.length + 1);
return colors[randomInt];
}
const userStillOnPage = true;
function f1(newInterval, continueWith) {
target.style.background = randomColor();
if (userStillOnPage) {
setTimeout(continueWith || f1, newInterval || 1000);
}
}
f1();
This method makes it easy to do all kinds of things like make the loop go faster by changing the interval or even injecting a different continuation function. It's quite powerful and easily abstracted to something very generic!
You can infinitely loop your javascript with setInterval:
<html>
<head>
<style>
#gallery {
width: 500px;
height: 300px;
background-color: red;
}
</style>
</head>
<body onload="f1()">
<div id="gallery">
</div>
</body>
<script type="text/javascript">
function f1(){
setInterval(oneSecondFunction, 9000);
};
function oneSecondFunction() {
setTimeout(
function() {
document.getElementById("gallery").style.backgroundColor = "blue";
}, 3000);
setTimeout(
function() {
document.getElementById("gallery").style.backgroundColor = "red";
}, 6000);
}
</script>
</html>
document.addEventListener('DOMContentLoaded', init);
function init() {
var target = document.getElementById('gallery');
setInterval(function() {
target.style.backgroundColor = getRandomColor();
}, 1000)
// From http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
}
I am trying to apply some classes to html elements via foor loop. The problem is that the loop variable doesn't work correctly.
'use strict'
window.onload = function(){
var elements = document.getElementsByTagName("div")
for(var i = 0; i < elements.length; i++){
elements[i].addEventListener("click", a(this, i), false)
}
function a(e, x){
if(!e.className){
e.className = "class".concat(x)
}
else {
e.classList.remove(e.className)
}
}
}
div{
background-color: red;
}
.class0{
background-color: blue;
}
.class1{
background-color: purple;
}
As #Patrick suggested do this:
window.onload = function(){
var elements = document.getElementsByTagName("div")
for(var i = 0; i < elements.length; i++){
elements[i].addEventListener("click", a.bind(window, elements[i],i), false)
}
function a(e, x){
if(!e.className){
e.className = "class".concat(x)
}
else {
e.classList.remove(e.className)
}
}
}
You were invoking the function a and assigning its result as an event handler.
With bind you create a function that will invoke a passing as arguments the element and the index.
Apologies for the basic question. It's hard to find information about JS event handling without finding an explanation that includes jQuery, and I'm trying to manipulate the DOM with pure Javascript. It's been helping me better understand how the browser works.
I'm trying to call a function to add an additional class to elements with the same class.
Can someone explain the correct syntax here?
Is it necessary to reference the ID?
I've tried a number of approaches. Thanks so much.
function animateSquare(e) {
var id = e.target.id
var el = document.getElementById(id);
el.className = el.className + "newClass";
};
window.onload = function() {
var anim = document.getElementsByClassName("squareThing");
for (var i = 0; i < anim.length; i++) {
anim[i].click(function(e) {
animateSquare(e);
});
}
}
<div class="squarething" id="one"></div>
<div class="squarething" id="two"></div>
The standard Javascript method to add event bindings, analogous to .on() in jQuery, is addEventListener.
And when you add a class to el.className, you need to include a space before it, to separate it from the existing classes.
You don't need to use getElementById(id), since e.target is the element itself -- you're getting the element, getting its ID, and then looking up the element again by ID, which is redundant.
function animateSquare(e) {
var el = e.target;
el.className = el.className + " newClass";
};
window.onload = function() {
var anim = document.getElementsByClassName("squarething");
for (var i = 0; i < anim.length; i++) {
anim[i].addEventListener('click', function(e) {
animateSquare(e);
});
}
}
.squarething {
width: 50px;
height: 50px;
background-color: green;
margin: 2px;
}
.newClass {
background-color: red;
}
<div class="squarething" id="one"></div>
<div class="squarething" id="two"></div>
This should be enough. Try it:
function animateSquare() {
this.className += " newClass";
}
window.onload = function() {
var anim = document.getElementsByClassName("squarething");
for (var i = 0; i < anim.length; i++) {
anim[i].onclick = animateSquare;
}
}
.squarething {
padding: 1em;
margin: .5em;
float: left;
background: blue;
}
.squarething.newClass {
background: orange;
}
<div class="squarething" id="one"></div>
<div class="squarething" id="two"></div>
.click(handler) is a jQuery method - you want the .onclick or addEventListener methods:
window.onload = function() {
var anim = document.getElementsByClassName("squarething");
for (var i = 0; i < anim.length; i++) {
anim[i].onclick = animateSquare;
}
}
You can also use this inside your handler function:
function animateSquare(e) {
this.className = el.className + "newClass";
};