How to handle onclick event of a button? - javascript

In the below code,
<!DOCTYPE html>
<html>
<head>
<title>Button events</title>
<meta charset="UTF-8">
<style type="text/css">
button{
background-color: #00FFFF;
border: 2px solid orange;
border-radius: 10px;
width: 60px;
height: 30px;
color:white;
}
</style>
</head>
<body>
<script type="text/javascript">
document.body.lastElementChild.onclick = changeColor;
function changeColor(){
if(document.body.lastElementChild.innerHTML == "Like"){
document.body.lastElementChild.style.background-color = "#FF9966";
document.body.lastElementChild.innerHTML = "Unlike";
}else{
document.body.lastElementChild.style.background-color="#00FFFF";
document.body.lastElementChild.innerHTML = "Like";
}
}
</script>
<button type="button" name="LikeUnlike">Like</button>
</body>
</html>
error is thrown at line document.body.lastElementChild.style.background-color = "#FF9966";. Error is Invalid left-hand side in assignment.
How do I resolve this error?
Note: yet to learn JQuery

First of all you need to use element.style.backgroundColor instead of element.style.background-color.
Here is a list of the JS equivalent of CSS attributes.
Your second problem is that your script executed before the <button> is loaded, thus making the script the current lastElementChildof body.
You can solve this by wrapping your script in window.onload:
(Also, selecting your button with document.body.lastElementChild is bound to give you errors since you most likely at some point will add something after the button)
<!DOCTYPE html>
<html>
<head>
<title>Button events</title>
<meta charset="UTF-8">
<style type="text/css">
button {
background-color: #00FFFF;
border: 2px solid orange;
border-radius: 10px;
width: 60px;
height: 30px;
color: white;
}
</style>
</head>
<body>
<script type="text/javascript">
window.onload = function() {
var likeButton = document.getElementById("like-button");
likeButton.onclick = changeColor;
function changeColor() {
if (likeButton.innerHTML == "Like") {
likeButton.style.backgroundColor = "#FF9966";
likeButton.innerHTML = "Unlike";
} else {
likeButton.style.backgroundColor = "#00FFFF";
likeButton.innerHTML = "Like";
}
}
}
</script>
<button type="button" name="LikeUnlike" id="like-button">Like</button>
</body>
</html>

background-color is not a valid JavaScript identifier. For setting it with DOM style object, it should be backgroundColor in camel case.
More info on DOM style object at http://www.w3schools.com/jsref/dom_obj_style.asp

Check out my demo
JS
document.body.lastElementChild.onclick = changeColor;
function changeColor(){
if(document.body.lastElementChild.innerHTML == "Like"){
document.body.lastElementChild.style.backgroundColor = "#FF9966";
document.body.lastElementChild.innerHTML = "Unlike";
}else{
document.body.lastElementChild.style.backgroundColor ="#00FFFF";
document.body.lastElementChild.innerHTML = "Like";
}
}

I think you should use document.body.lastElementChild.style["background-color"] to set color for element

not background-color but backgroundColor . Try this and see if works
document.body.lastElementChild.style.backgroundColor = "#FF9966";
the total code:
document.body.lastElementChild.onclick = changeColor;
function changeColor(){
if(document.body.lastElementChild.innerHTML == "Like"){
document.body.lastElementChild.style.backgroundColor = "#FF9966";
document.body.lastElementChild.innerHTML = "Unlike";
}else{
document.body.lastElementChild.style.backgroundColor ="#00FFFF";
document.body.lastElementChild.innerHTML = "Like";
}
}

You use this code. It is working fine.
<!DOCTYPE html>
<html>
<head>
<title>Button events</title>
<meta charset="UTF-8">
<style type="text/css">
button{
background-color: #00FFFF;
border: 2px solid orange;
border-radius: 10px;
width: 60px;
height: 30px;
color:white;
}
</style>
</head>
<body>
<script type="text/javascript">
document.body.lastElementChild.onclick = changeColor;
function changeColor(){
if(document.body.lastElementChild.innerHTML == "Like"){
document.body.lastElementChild.style.backgroundColor =
"#FF9966";
document.body.lastElementChild.innerHTML = "Unlike";
}else{
document.body.lastElementChild.style.backgroundColor="#00FFFF";
document.body.lastElementChild.innerHTML = "Like";
}
}
</script>
<button type="button" name="LikeUnlike" onclick="changeColor
()">Like</button>
</body>
</html>

You can use Jquery for assign or remove a css class, to add color to your button, with this code:
<script>
$(function() {
$('button').on('click', function() {
$(this).toggleClass('other-color');
});
});
</script>
the toggleClass function is to add and remove a css class,
"othercolor" is your class css with the styles to your button.
Include jquery with this script before </body> and before the code above:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function() {
$('button').on('click', function() {
$(this).toggleClass('other-color');
});
});
</script>
I hope it helps you.

Related

Why doesn't jQuery function toggleClass() work?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../jquery/jquery.js"></script>
<style type="text/css" rel="stylesheet">
#btn {
background: green;
color: #fff;
padding: 15px;
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<script>
$(() => {
$("#btn").click(() => {
if ($("#btn").hasClass("green")) {
$("#btn").css("backgroundColor", "red");
}
else if ($("#btn").hasClass("red")) {
$("#btn").css("backgroundColor", "green");
}
});
});
</script>
<button id="btn">Button</button>
</body>
</html>
I want the button to change its color either to red if it's green or to green if it's red. So I use toggleClass() to implement that.
Question: why doesn't it work?
It is almost certainly working but there are no CSS rules for the class "background" in the code you posted. The function is for adding/removing an entry from the class list of an element, not for directly manipulating style object properties.
If you do switch from .toggleClass() to .css(), you'll find that switching a property from one value to another immediately will have no visible effect. The browser will effectively ignore the first update.
Your are change class name using toggle not the rule within the class. But you can iverride it by adding inline style, like:
$("#btn").css("background", "red");
$(() => {
$("#btn").click(function () {
const bgColor = this.style.backgroundColor;
$(this).css("backgroundColor", bgColor === 'green' ? "red" : "green");
});
});
#btn {
color: #fff;
padding: 15px;
font-size: 24px;
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" style="background-color:green;">Button</button>
It is perfectly correct to use the .toggleClass() method...
But the argument is a string of space separated classnames.
And, of course, you have to define those class rules in your style sheet.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!--script src="../jquery/jquery.js"></script-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css" rel="stylesheet">
#btn {
/*background: green;*/
color: #fff;
padding: 15px;
font-size: 24px;
font-weight: bold;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
</style>
</head>
<body>
<script>
$(() => {
$("#btn").click(() => {
$("#btn").toggleClass("red green");
});
});
</script>
<button id="btn" class="green">Button</button>
</body>
</html>

How to toggle audio play/pause with one button

I never really worked with javascript before, but I tried googling for a solution to how to make a play/pause button for audio - and I found what appears to be a good and simple solution on this site:
How to toggle audio play() pause() with one button or link?
(PS. I don't have reputation poins enough to comment on Iceman's solution and ask him directly what might be wrong - I would have if I could.)
But, when I paste the code snippets into my document, nothing happens (the resulting text isn't clickable).
Could some of you take a look and tell me what I'm doing wrong? It's very possible it's something stupid, but I can't see it myself.
Index.html so far:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Ukendt Navn ...</title>
<script>
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause()
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
</script>
<style type="text/css">
#content {
border: 1px solid blue;
margin: auto;
max-width: 20vw;
margin-top: 30vw;
color: black;
}
</style>
</head>
<body>
<div id="content">
<audio id="myAudio" src="birds.mp3" preload="auto"></audio>
<a onClick="togglePlay()">Click here to hear.</a>
</div>
</body>
</html>
My test site: http://wyrdling.com/other/ukendtnavn/
You are trying to call document.getElementById("myAudio") before the element is loaded, therefore you can either call it after the page fully loaded, or place the script right before the end of body tag.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Ukendt Navn ...</title>
<script>
window.addEventListener('load', function(){
var myAudio = document.getElementById("myAudio");
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
});
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause()
} else {
myAudio.play();
}
}
</script>
<style type="text/css">
#content {
border: 1px solid blue;
margin: auto;
max-width: 20vw;
margin-top: 30vw;
color: black;
}
</style>
</head>
<body>
<div id="content">
<audio id="myAudio" src="http://wyrdling.com/other/ukendtnavn/birds.mp3" preload="auto"></audio>
<a onClick="togglePlay()">Click here to hear.</a>
</div>
</body>
</html>

One of Multiple Scripts in HTML Sheet Not Working

I am trying to have multiple scripts run in my html sheet, and it seems to not be working. All the other scripts work except for the script for the blinking function. I don't see what the problem is. Can you find the issue with my code? Thanks in advance!
Here is my code below:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: coral;
color: white;
}
.text2{
color: white;
width: 100px;
float: right;
padding-top: 10px;
}
</style>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".btn1").on('click',function(){
$("p").hide();
$(".text2").hide()
$('body').css("background", "black");
});
});
</script>
<script>
//blink
var element = $(".text2");
var shown = true;
setInterval(toggle, 500);
function toggle() {
if(shown) {
element.hide();
shown = false;
} else {
element.show();
shown = true;
}
}
</script>
</head>
<body>
<p>This is a paragraph.</p>
</div>
<div class="text2">
-- : --
</div>
<button class="btn1">online</button>
</body>
</html>
The second script must be inside a JQuery function.
$(document).ready(function(){
var element = $(".text2");
var shown = true;
setInterval(toggle, 500);
function toggle() {
if(shown) {
element.hide();
shown = false;
} else {
element.show();
shown = true;
}
}
});
The second script's contents should be in the document ready handler otherwise the code attempts to locate and work with the .text2 element before that element has been parsed into memory.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: coral;
color: white;
}
.text2{
color: white;
width: 100px;
float: right;
padding-top: 10px;
}
</style>
<link rel="stylesheet" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".btn1").on('click',function(){
$("p").hide();
$(".text2").hide()
$('body').css("background", "black");
});
var element = $(".text2");
var shown = true;
setInterval(toggle, 500);
function toggle() {
if(shown) {
element.hide();
} else {
element.show();
}
shown = !shown;
}
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<div class="text2">-- : --</div>
<button class="btn1">online</button>
</body>
</html>

Traffic light using javascript

I want create traffic light controller.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>isiqfor</title>
<link rel="stylesheet" href="style.css">
</head>
<body onload="timer;">
<div id="isiqfor">
<div class="green"></div>
<div class="yellow"></div>
<div class="red"></div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS code:
#isiqfor{
border: 10px solid black;
padding: 10px 3px;
width: 50px;
}
#isiqfor>div{
width:50px;
height: 50px;
border-radius: 50%;
opacity: .3;
}
.green{
background-color: green;
}
.yellow{
background-color: yellow;
}
.red{
background-color: red;
}
And JS file:
function myFun () {
// body...
var green=document.getElementsByClassName("green")[0];
var red=document.getElementsByClassName("red")[0];
var yellow=document.getElementsByClassName("yellow")[0];
green.style.opacity=1;
setTimeout(function () {
/* body... */
green.style.opacity=.3;
red.style.opacity=.3;
yellow.style.opacity=1;
},5000);
setTimeout(function () {
/* body... */
green.style.opacity=.3;
red.style.opacity=1;
yellow.style.opacity=.3;
},7000);
setTimeout(function () {
/* body... */
green.style.opacity=1;
red.style.opacity=.3;
yellow.style.opacity=.3;
},12000);
}
var timer = setInterval(function () {
/* body... */
myFun()
},13000);
But problem is when page loads it must wait 13 second for beginning traffic light.How can solve this problem? I want when page loads green light has switched.
Have you tried calling myFun straight away after your timer is set? See the call to myFun added to the bottom of the following code:
var timer = setInterval(function () {
/* body... */
myFun()
},13000);
myFun();//Call 'myFun' straight away...
I created a simple traffic light system! Try this one.
I used jquery to simplify the attribute selection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Traffic Lights</title>
</head>
<body>
<p>Demonstrate traffic lights system</p>
<div id="div1" style="width:80px;height:80px;background-color:white;border: 1px solid #000;"></div><br>
<div id="div2" style="width:80px;height:80px;background-color:white;border: 1px solid #000;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:white;border: 1px solid #000;"></div>
</body>
<script>
$(document).ready(function () {
var state = 0;
setInterval(function () {
// state 0 > STOP
// state 1 > READY
// state default > GO
switch (state) {
case 0:
state = 1;
$('#div3').css({ 'background-color': 'white' });
$('#div1').css({ 'background-color': 'red' });
break;
case 1:
state = 3
$('#div1').css({ 'background-color': 'white' });
$('#div2').css({ 'background-color': 'yellow' });
break;
default:
state = 0;
$('#div2').css({ 'background-color': 'white' });
$('#div3').css({ 'background-color': 'green' });
}
}, 2000);
});
</script>
</html>

JQuery: Appending to an element created in another function

I created a div like so:
$(document).ready(function() {
$(document.createElement("div")).attr("id", "container").appendTo("body");
});
and then later, dynamically I want to append some stuff to it, so in another function I call
$(newElement).appendTo("#container");
but it doesn't do anything. The div is still there, but it is empty. If I change the code to
$(newElement).appendTo("body");
it works fine. Any ideas on what I'm doing wrong?
Here is a full example of my code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document.createElement("div")).attr("id", "container").appendTo("body");
});
function add() {
var newElement = $(document.createElement("div")).attr("id", "inner");
$(newElement).appendTo("#container");
}
</script>
<style type="text/css">
#inner{
background-color: black;
height: 200px;
width:100px;
}
</style>
</head>
<body>
<script language="JavaScript" type="TEXT/JAVASCRIPT">
add();
</script>
</body>
</html>
Your add() function is being called before $(document).ready();
Change it to this and it should work:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document.createElement("div")).attr("id", "container").appendTo("body");
add();
});
function add() {
var newElement = $(document.createElement("div")).attr("id", "inner");
$(newElement).appendTo("#container");
}
</script>
<style type="text/css">
#inner{
background-color: black;
height: 200px;
width:100px;
}
</style>
</head>
<body>
</body>
</html>
Which could be condensed to:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
$(function() {
$("<div/>", { id : "container" }).appendTo("body");
$("<div/>", { id : "inner"}).appendTo("#container");
});
</script>
<style type="text/css">
#inner{
background-color: black;
height: 200px;
width:100px;
}
</style>
</head>
<body>
</body>
</html>

Categories