I have some text and a button. Once user clicks a button I want the text's background to change color to green and back. But nothing happens if I click the button...
Here's the JS script:
<script>
function bright(){
kontakt = document.getElementById('kontakt');
kontakt.bgcolor = '#A5DF00';
}
function dark(){
kontakt = document.getElementById('kontakt');
kontakt.bgcolor = '#000000';
}
function highlight(){
setTimeout(bright() , 1000);
setTimeout(dark() , 1000);
}
</script>
I call the highlight() from the button's onclick attribute like this: onclick='highlight()'.
The text with id kontakt is always on the page.
Any clue?
The css property are accessible through the style property:
var kontakt = document.getElementById('kontakt');
function bright(){
kontakt.style.backgroundColor = '#A5DF00';
}
function dark(){
kontakt.style.backgroundColor = '#000000';
}
All CSS properties can be accessed the same way. if the property has a dash in it z-index just use the camel case notation.
Ex: kontakt.style.zIndex
you also need to update your setTimeout like so:
function highlight(){
setTimeout(bright , 1000);
setTimeout(dark , 2000);
}
In your case you were calling the functions and passing whatever they return to setTimeout. You also want to change the timer for the first function to happen after a second, and the next follows one second after.
According to your code, when highlight() is called it will wait for one second and then turn the background from whatever it was to green and immediately to black, as fast as it possibly can. I'm guessing that you don't see it flash green because that's faster than the browser renders or your eye can detect.
Try changing setTimeout(dark , 1000); to setTimeout(dark , 1500);.
jsfiddle example here modified based on this SO answer.
<span id='kontakt' onClick="highlight(this);">Click me to see me change color and back</span>
function highlight(obj){
var orig = obj.style.color;
obj.style.color = '#f00';
setTimeout(function(){
obj.style.color = orig;
}, 5000);
}
I would recommend using jquery for this problem. You can download it here. And use it by updating your head-section in your html-document with
<head>
other code...
<script src="directory/where/you/installed/jquery"></script>
</head>
now you can highlight the text with the id 'kontakt' by using following functions:
<script>
$(document).ready(function(){ //this ensures that all elements have been loaded before you are executing any js
function highlight(){
$("#kontakt").css("background-color", "#A5DF00");
setTimeout(function(){
$("#kontakt").css("background-color", "#000000");
}, 1000);
};
// now to execute highlight() by clicking on the button you use
$("#id-of-the-button").click(highlight();
// there is no further need of the onclick attribute for your button
}
</script>
For more information on how to use jquery you can visit w3schools. They have a lot of very nice tutorials for exactly those tasks.
Related
I am working on one JavaScript project, where I need to toggle between Celsius and Fahrenheit.
The HTML is here
<button onclick="toggleCF();" id="toggleCF" class="button">Toggle C/F</button>
And here is the JavaScript Function
this.toggleCF = function() {
console.log('click');
var fahrenheit = document.getElementById('toggleFahrenheit');
var celsius = document.getElementById('toggleCelsius');
if (fahrenheit.style.display === 'none') {
fahrenheit.style.display = 'block';
celsius.style.display = 'none';
} else {
fahrenheit.style.display = 'none';
celsius.style.display = 'block';
}
}
The CSS I used is given
.temperature-celsius {
}
.temperature-fahrenheit {
display: none;
}
If you want to check this application live here is the link
Please click on this link to see app in running form
If you visit the above link and check, you will find that on first click the toggle didn't work. But when you click the second time then it starts working normally.
When the app is first loaded, both the toggleFahrenheit and toggleCelsius divs have no style attribute. They are getting display rules from the CSS, true, but they have no style on themselves.
So think about what your code sees, then. fahrenheit.style.display is null because that block doesn't have the style attribute yet. Therefore, fahrenheit.style.display === 'none' evaluates to false. As a result, the else block is executed and you end up displaying Celsius. Unfortunately, this is the default block which is shown, so the first click doesn't do anything.
The second click works because after the code executes once, now both div blocks have a style attribute.
To fix this, you should either put default style attributes onto the div tags or flip the logic in the code so you check on the Celsius block first, since that's the default display.
Personally, I would use classes to toggle display behaviour instead.
function toggle() {
var fahrenheit = document.getElementById("fahrenheit");
var celsius = document.getElementById("celsius");
fahrenheit.classList.toggle('hide');
celsius.classList.toggle('hide');
}
.hide { display: none; }
<div id="fahrenheit" class="hide">-40 F</div>
<div id="celsius">-40 C</div>
<button onclick="toggle()">Toggle</button>
And yes, I use -40 degrees in the example because I'm lazy and I happen to know this is the same temperature in both systems (:
It does not work because this if (fahrenheit.style.display === 'none') will return NULL as there is no inline style on the element. this method won't "look" at CSS, it only works for inline styles. You could try this:
var element = document.getElementById('toggleFahrenheit'),
style = window.getComputedStyle(element),
top = style.getPropertyValue('top');
to check the CSS properties in pure JS or you could use JQuery which would solve it in one line of code.
This often happen most of the time on your css content not being been loaded up fully i have my issue solved with the following code:
function yourFunction() {
document.addEventListener("DOMContentLoaded", function(){
// you works start here
});
}
The simple solution is to use the EventListener .
I had the same problem with the onclick but when using :
const myEl = document.getElementById('myBtn');
myEl.addEventListener('click', function () {
//Your code here
});
It works on first click!
i found a very simple javascript function for a slideshow (here).
It works perfectly, but i want to change something about the control buttons. Right now, the play/pause button displays it's own name, like this:
<button class="controls" id="pause">Pause</button>
The javascript is set to run a function called pauseSlideshow under certain circumstances which not only pauses/resumes the slideshow, but also changes the displayed content of the button from "pause" to "play":
var playing = true;
var pauseButton = document.getElementById('pause');
function pauseSlideshow() {
pauseButton.innerHTML = 'Play';
playing = false;
clearInterval(slideInterval);
}
now, what i want to do is to leave the button empty and work width background images, and to do that i planned to do a simple class swap whenever the pauseSlideshow function is triggered. So, first i added a class called pause to the button with the desired background image set in the style:
<button class="controls pause" id="pause"></button>
and next i was going to do something like this:
var playing = true;
var pauseButton = document.getElementById('pause');
function pauseSlideshow() {
pauseButton.removeClass('pause');
pauseButton.addClass('play');
playing = false;
clearInterval(slideInterval);
}
(where play is another class with a different background image). Sufficient to say, as soon as pauseSlideshow runs, the function crashes. I'm writing something wrong or in the wrong place, but i know that the approach is viable.
please, can anybody point out the error?
EDIT:
Use $(pauseButton).removeClass('pause'); and
$(pauseButton).addClass('play');. addClass and removeCalss are jQuery
methods. And you need to add jQuery reference too. – user3698428
document.getElementById("pause") does not return a jQuery element.
.removeClass() and .addClass() are jQuery functions. So basically you
are trying to call jQuery functions on a non-jQuery element and it's
throwing an error. Change it to var pauseButton = $("#pause"); or
$(pauseButton).removeClass(...); $(pauseButton).addClass(...);
when i try either way, console returns: Uncaught ReferenceError: $ is not defined
When working in pure javascript, you should use this to add or remove class:
pauseButton.classList.remove('pause');
pauseButton.classList.add('play');
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
So as you can see on https://www.sketchapp.com/ they got something cool midway through the page, as you can see it changes the text automatically (Sketch is made for Chaning text here like you) after some time; and I was wondering how they did that and how it's called.
I'm trying to recreate something similar, Thanks
That you need is either a setInterval if you want the text to change on approximately the same time for an indefinite period or you setTimeout if you want to change the text only once. Below it is a snippet that uses the setTimeout as an example:
document.addEventListener('DOMContentLoaded', function(){
setTimeout(function(){
var div = document.getElementById('js-text');
div.innerHTML = "Replaced <span class='redText'>Text</span>";
}, 1000);
});
.redText{
color: red;
}
<div id="js-text">Initial Text</div>
I am trying to perform a transition state from Transition State 1 to Transition State 2
The technology I am using to accomplish this JavaScript because JavaScript can dynamically "change the content of HTML elements" - JavaScript
Here is JFiddle
I saw that to change the src of an image tag in html, you have to execute this line of code (From Change Img Src)
document.getElementById("imageid").src="../template/save.png";
Here is my entire JavaScript code for the changing image portion(from my JFiddle)
(function() {
alert("got here");
function pageLoad() {
document.getElementById("choice1").onclick = getPicture("http://i.imgur.com/e95oMVZ.jpg");
document.getElementById("choice2").onclick = getPicture("http://imgur.com/dOlZ19H");
}
function getPicture(imageUrl) {
document.getElementById("picture").src = imageUrl;
}
window.onload = pageLoad;
})();
I made sure I was follow conventions for JavaScript Arguments, checked over my ids, and coded an alert statement to make sure the JavaScript was being executed.
After all of that, when I click on choice2, the image still doesn't change... Does anyone know what the issue could be?
You need to set onclick to a function. You're calling the function immediately, not when the element is clicked.
function pageLoad() {
document.getElementById("choice1").onclick = function() {
getPicture("http://i.imgur.com/e95oMVZ.jpg");
};
document.getElementById("choice2").onclick = function() {
getPicture("http://imgur.com/dOlZ19H");
};
}
I have been scratching my head for a while, and I can't figure out how I could locally store (HTML5 local storage) a change to the styling of a certain div made by a javascript function. I have a button which allows the user to change the background colour of the container by changing the css (inline). Does anyone know of a way of storing this change?
Demo
JS (running at load or DOMContentLoaded):
var bgColor = document.getElementById('bgcolor');
bgColor.onchange = function() {
document.body.style.backgroundColor = this.value;
localStorage.setItem('bgColor', this.value);
};
bgColor.value = localStorage.getItem('bgColor');
bgColor.onchange();
HTML:
<input id="bgcolor" />
Or, if you use jQuery,
$('#bgcolor')
.val(localStorage.getItem('bgColor'))
.change(function() {
$('body').css({'background-color': this.value});
localStorage.setItem('bgColor', this.value);
})
.change();
Demo
So you have a function like:
function changeDivBackground(div, bg) {
/* ...change the background... */
}
There are two steps:
Remember the value:
function changeDivBackground(div, bg) {
/* ...change the background... */
localStorage["theDivBackground"] = bg;
}
In a script tag at the end of the page, see if you have a value and use it:
var bg = localStorage["theDivBackground"];
if (bg) {
changeDivBackground(/*...get the div...*/, bg);
}
The script tag is at the end of the page in #2 so that the div will exist by the time it's run.
Store the value to local storage. Then write a JavaScript function that retrieves the value and applies it.