I want to change the background colour of header(h1) whenever I click on the page.
Here is my code:
document.addEventListener('click', func);
function func(){
var mainHeading = document.querySelector('h1');
var colors = ['cyan', 'black', 'brown'];
for(let b = 0; b <= colors.length; b++){
mainHeading.style.backgroundColor = colors[b];
}
}
You shouldn't use a for loop for that.
Simply keep track of which color you're currently at with a variable :
let color = 0; // Variable to keep track of the color
let colors = ['cyan', 'black', 'brown'];
document.addEventListener('click', func);
function func() {
let mainHeading = document.querySelector('h1');
color = color < colors.length - 1 ? color+1 : 0; //Increment your color or reset it
mainHeading.style.backgroundColor = colors[color];
}
<h1>Test</h1>
You keep looping thru all colours in the array with every click
Instead, you need to keep track of the last colour used and updated it with every event.
Also, you do not need to declare the array of colours every time the event is handled. You can just declare it once (outside the handler) and use it many times.
Something along the lines of:
var currentColorIndex = 0;
var colors = ['cyan', 'black', 'brown'];
document.addEventListener('click', func);
function func() {
var mainHeading = document.querySelector('h1');
// reset color
if (currentColorIndex >= colors.length) {
currentColorIndex = 0;
}
mainHeading.style.backgroundColor = colors[currentColorIndex];
currentColorIndex++;
}
<h1>Title</h1>
You need to save the state of the color. Otherwise, your for loop will always set the color to the last element
document.addEventListener('click', func);
function func(){
var colors = ['cyan', 'black', 'brown'];
var idx = ((this.idx ? this.idx : 0) + 1) % colors.lengh;
this.idx = idx;
var mainHeading = document.querySelector('h1');
mainHeading.style.backgroundColor = colors[idx];
}
}
Related
In the below javaScript code:
function webSocketStart()
{ //onclick() of a button
document.getElementById("button").disabled = true;
var wsock = new WebSocket("ws://127.0.0.1:1234/websock");
wsock.onmessage = function (evt)
{
var map = JSON.parse(evt.data)
var myTable = document.getElementById("myTable");
var rows = myTable.getElementsByTagName("tr")
var existing = false
for (var i = 1; i < rows.length; i++) {
if (rows[i].getElementsByTagName("td").length > 0) {
if (rows[i].cells[0].textContent.trim().localeCompare(map['Key'].trim()) == 0){
rows[i].cells[1].textContent = map['Value'] // cell color should change and unchange for two seconds
existing = true
break
}
}
}
if (!existingApp){
var row = myTable.insertRow(1); // New row at the first position
var keyCell = row.insertCell(0)
keyCell.textContent = map['Key']
keyCell.style.backgroundColor = 'yellow'
setInterval(function(){
keyCell.style.backgroundColor = 'white'
}, 2000);
var valueCell = row.insertCell(1)
valueCell.textContent = map['Value']
valueCell.style.backgroundColor = 'yellow'
setTimeout(function(){
valueCell.style.backgroundColor = 'white'
}, 2000);
}
Line 17, 26 & 27 have comments for color change and unchange
Edit:
Made code changes with setTimeout() but some cells does not change back to white
for (var i = 1; i < rows.length; i++) {
if (rows[i].getElementsByTagName("td").length > 0) {
if (rows[i].cells[0].textContent.trim().localeCompare(map['Key'].trim()) == 0){
rows[i].cells[1].textContent = map['Value']
rows[i].cells[1].style.backgroundColor = 'yellow' // color change
existing = true
setTimeout(function(){
rows[i].cells[1].style.backgroundColor = 'white'
}, 2000);
break
}
}
}
if (!existing){
var row = myTable.insertRow(1);
keyObj = row.insertCell(0)
keyObj.textContent = map['Key']
keyObj.style.backgroundColor = 'yellow' // color change
setInterval(function(){
keyObj.style.backgroundColor = 'white'
}, 2000);
keyObj = row.insertCell(1)
keyObj.textContent = map['Value']
keyObj.style.backgroundColor = 'yellow' // color change
setTimeout(function(){
keyObj.style.backgroundColor = 'white'
}, 2000);
}
Using CSS & JavaScript,
1) How to change and unchange the color of the background in table cell, for 2 seconds? after setting of values in table cell
2)
As table element has style properties, Can we achieve the same without CSS rules? rows[i].cells[1].style.backgroundColor = 'yellow'
You can just use sleep function with the seconds inside like sleep(2) for 2 seconds
Is it what's you want
You're already getting the element so you would add a class in JS like this:
el.classList.add('className'); Then you need to set a timer setInterval(function, milliseconds) that removes the class after a set amount of time. The CSS will then revert back to default. I added a CSS transition to the color so it's not as jarring when it changes.
(click handler is just for the example)
var removeClass = function(targ){
if(targ.classList.contains('highlight')){
targ.classList.remove('highlight');
}
}
document.getElementById('myEl').addEventListener('click', function () {
var myEl = this
myEl.classList.add('highlight');
var myTimer = setInterval(function(){removeClass(myEl)},2000);
});
#myEl {
width: 30px;
height: 30px;
margin: 10px;
background-color: aqua;
transition: background 0.25s ease;
}
#myEl.highlight {
background-color: orange;
}
<div id='myEl'></div>
Click the box to activate the timer
I'm grouping a few elements using snapSVG's group method, pushing them to an array and applying the drag method on the array elements by looping through each element.
Could you please help me in accessing the index postion of the dragged element (grps[i]) in the drag stop handler.
g1 and var g2 are the two gropus.
grps is the array that holds the two groups.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.5.1/snap.svg-min.js"></script>
</head>
JavaScript
var s = Snap(800, 600);
var grps = [];
var objects = [];
var red = s.rect(50, 50, 200, 200).attr({
fill: "red"
});
var green = s.rect(60, 60, 100, 100).attr({
fill: "green"
});
var g1 = s.group(red, green);
grps.push(g1);
var red = s.rect(300, 50, 200, 200).attr({
fill: "red"
});
var green = s.rect(310, 60, 100, 100).attr({
fill: "green"
});
var g2 = s.group(red, green);
grps.push(g1, g2);
var drag_move = function(dx, dy) {
this.attr({
transform: this.data('origTransform') + (this.data('origTransform') ? "T" : "t") + [dx, dy]
});
};
var drag_start = function() {
this.data('origTransform', this.transform().local);
};
var drag_stop = function(i) {
console.log("finished dragging");
console.log(i);
};
for (i = 0; i < grps.length; i++) {
grps[i].drag(drag_move, drag_start, drag_stop);
}
JsBin Link: http://jsbin.com/tonazosicu/10/edit?js
Thanks
You can using Function.prototype.bind() to preset some parameters like below
for (i = 0; i < grps.length; i++) {
grps[i].drag(drag_move, drag_start, drag_stop.bind(null, i));
}
Then on drag_stop you can access them like below.
var drag_stop = function(index, event) {
console.log("finished dragging");
console.log(index);
console.log(event);
};
One can achieve the same thing (in lastest versions of Snap I think) with...
grps.ForEach( function( el, i ) {
el.drag(drag_move, drag_start, drag_stop.bind(null, i))
};
But ultimately you don't need to use i, if you just use 'this' in the handler in most cases, and can simply do....
grps.ForEach( function( el ) {
el.drag(drag_move, drag_start, drag_stop)
};
I am very new to JavaScript and trying to learn to do some functional things. I'm trying to get more comfortable with arrays. In this, I want the onClick in the HTML to cycle to EACH array value (color) and style the <p> with each one. Currently it just goes to the end, and I understand why it does that, but I don't know how to produce the result I want.
My (relevant) HTML:
<p id="pg">Hi, this is a string of text.</p>
<button type="button" onclick="change()">Click Me!</button>
My JS:
var colors = ['#3498db', '#e67e22', '#16a085', '#f39c12', '#2c3e50', '#7f8c8d', '#2980b9'];
function change()
{
for (i = 0; i < colors.length; i++) {
x=document.getElementById("pg"); // Find the element
x.style.color=colors[i]; // Change the style
}
}
Should I even use loops for this? Thank you for any help.
You need to use either global variable below, or alternatively run a loop to find the color and get next. Here is the first approach:
var colors = ['#3498db', '#e67e22', '#16a085', '#f39c12', '#2c3e50', '#7f8c8d', '#2980b9'];
var i = 0;
function change()
{
x=document.getElementById("pg");
x.style.color=colors[i++];
if(i == colors.length) i = 0;
}
Try this :
var colors = ['#3498db', '#e67e22', '#16a085', '#f39c12', '#2c3e50', '#7f8c8d', '#2980b9'];
function change()
{
setColor(0);
}
function setColor(i) {
if(i >= colors.length);
return;
document.getElementById("pg").style.color = colors[i];
setTimeout(function() {
setColor(i + 1);
}, 1000);
}
You can change the second parameter of setTimeout to decide how many milliseconds to wait before changing color again.
You can cycle colors like this:
var colors = ['#3498db', '#e67e22', '#16a085', '#f39c12', '#2c3e50', '#7f8c8d', '#2980b9'];
var i = 0;
function change() {
var x = document.getElementById("pg");
x.style.color = colors[i++ % colors.length];
}
http://jsfiddle.net/A2JBL/
There are two important pieces in this code. The first is the timeout which changes the color each second. The second is that a closure is created to assure that the color variable is not changed within the function passed to setTimeout during the iterations of the loop.
var colors = ['#3498db', '#e67e22', '#16a085', '#f39c12', '#2c3e50', '#7f8c8d', '#2980b9'];
var timeouts = [];
function change()
{
clearTimeouts()
for (i = 0; i < colors.length; i++) {
var timeout = setTimeout(changeColor(colors[i]), 1000 * i);
timeouts.push(timeout);
}
}
function changeColor(color){
return function(){
var x=document.getElementById("pg"); // Find the element
x.style.color=color;
};
}
function clearTimeouts(){
for(var i = 0; i < timeouts.length; i++){
clearTimeout(timeouts[i]);
}
}
JS Fiddle: http://jsfiddle.net/4ryGJ/1
If you would prefer to only change the color on each click
var colors = ['#3498db', '#e67e22', '#16a085', '#f39c12', '#2c3e50', '#7f8c8d', '#2980b9'];
var color = 0;
function change()
{
color = (color == colors.length -1) ? 0: color;
x=document.getElementById("pg"); // Find the element
x.style.color=colors[++color];
}
I wanted to keep the colors changing on a certain word. Can anyone help me? This is what I have so far:
var myColor = document.getElementById("color");
var colorArray = ["#ffd464", "#2980b9", "#DC143C", "#3CB371", "#DA70D6", "#9400D3"];
var colorIndex = 0;
function changeColor() {
myColor.style.color('color', colorArray[colorIndex]);
colorIndex++;
if (colorIndex >= colorArray.length) {
colorIndex = 0;
}
}
setInterval(changeColor, 5000);
Thank you!
I would give a try this way, dont want to maintain an index:
function changeColor(){
var color = colorArray.shift(); //get the top color from array
colorArray.push(color); //push it to the end to cycle it
myColor.style['color'] = color ; //syntax error here
}
setInterval( changeColor,5000 );
and also
myColor.style.color('color', colorArray[colorIndex]);
should be
myColor.style['color'] = color ;
since color is a property of style attribute of the element and it is not a method.
Fiddle
i am working on a small application (phonegap) that scrolls a page of a book when the users pushed the audio-button to listen to the text at the same time. The general idea :-)
I have looked into the Marquee version, what works so far but it has some strange behaviour:
<marquee behavior="scroll" height="100%" vspace="0%" direction="up" id="mymarquee" scrollamount="3" scolldelay="1000" loop="1"> TEXT HERE </marquee>
with the "id="mymarquee" connected to the audio play button. This works but not recommanded as they say. Better to use a javascript version. So i found a cool version so far on the web, but it goes from the right to the left. Now i am not the best programmer in the world so i was wondering if someone could help adjust the script below so we can add a direction to it. This way the script would be multi-functional (for others as well) since i only need a scroll from top to bottom.
Here is the HTML part:
<script src="js/slideandfade.js" type="text/javascript"></script>
<DIV ID="fader" STYLE="text-align:right;"></DIV>
<SCRIPT TYPE="text/javascript">
fadeandscroll('TEXT HERE', '#676F77', '#DFF5FF', 40, 70, 250, 10);
</SCRIPT>
And this is the slideandfade.js
//Text fade
var bgcolor;
var fcolor;
var heading;
//Number of steps to fade
var steps;
var colors;
var color = 0;
var step = 1;
var interval1;
var interval2;
//fade: fader function
// Fade from backcolor to forecolor in specified number of steps
function fade(headingtext,backcolor,forecolor,numsteps) {
if (color == 0) {
steps = numsteps;
heading = "<font color='{COLOR}'>"+headingtext+"</strong></font>";
bgcolor = backcolor;
fcolor = forecolor;
colors = new Array(steps);
getFadeColors(bgcolor,fcolor,colors);
}
// insert fader color into message
var text_out = heading.replace("{COLOR}", colors[color]);
// write the message to the document
document.getElementById("fader").innerHTML = text_out;
// select next fader color
color += step;
if (color >= steps) clearInterval(interval1);
}
//getFadeColors: fills colors, using predefined Array, with color hex strings fading from ColorA to ColorB
//Note: Colors.length equals the number of steps to fade
function getFadeColors(ColorA, ColorB, Colors) {
len = Colors.length;
//Strip '#' from colors if present
if (ColorA.charAt(0)=='#') ColorA = ColorA.substring(1);
if (ColorB.charAt(0)=='#') ColorB = ColorB.substring(1);
//Substract red green and blue components from hex string
var r = HexToInt(ColorA.substring(0,2));
var g = HexToInt(ColorA.substring(2,4));
var b = HexToInt(ColorA.substring(4,6));
var r2 = HexToInt(ColorB.substring(0,2));
var g2 = HexToInt(ColorB.substring(2,4));
var b2 = HexToInt(ColorB.substring(4,6));
// calculate size of step for each color component
var rStep = Math.round((r2 - r) / len);
var gStep = Math.round((g2 - g) / len);
var bStep = Math.round((b2 - b) / len);
// fill Colors array with fader colors
for (i = 0; i < len-1; i++) {
Colors[i] = "#" + IntToHex(r) + IntToHex(g) + IntToHex(b);
r += rStep;
g += gStep;
b += bStep;
}
Colors[len-1] = ColorB; // make sure we finish exactly at ColorB
}
//IntToHex: converts integers between 0 - 255 into a two digit hex string.
function IntToHex(n) {
var result = n.toString(16);
if (result.length==1) result = "0"+result;
return result;
}
//HexToInt: converts two digit hex strings into integer.
function HexToInt(hex) {
return parseInt(hex, 16);
}
var startwidth = 0;
//scroll: Make the text scroll using the marginLeft element of the div container
function scroll(startw) {
if (startwidth == 0) {
startwidth=startw;
}
document.getElementById("fader").style.marginLeft = startwidth + "px";
if (startwidth > 1) {
startwidth -= 1;
} else {
clearInterval(interval2);
}
}
function fadeandscroll(txt,color1,color2,numsteps,fademilli,containerwidth,scrollmilli) {
interval1 = setInterval("fade('"+txt+"','"+color1+"','"+color2+"',"+numsteps+")",fademilli);
interval2 = setInterval("scroll("+containerwidth+")",scrollmilli);
}