I have a webpage that has a link set to change the background colour of the page, the colour of the link, & the link text. Here is my code:
<html>
<head>
<title>Title</title>
<script type="text/javascript">
function Lights() {
document.body.style.backgroundColor='#000000';
document.getElementById("on").innerHTML="Turn on the lights";
document.getElementById("on").style.color="#00ffff";
}
</script>
</head>
<body style="font-size:200px; text-align:center;">
Turn off the lights
</body>
</html>
I was wondering how I would set the JavaScript to reverse those statements when the link is clicked again so the page is back to the white background, the text is back to "Turn off the lights", & the link is back to the darker blue.
Thank you
You can use a variable to store the state and toggle based off that.
<script type="text/javascript">
var toggle = false;
function Lights() {
var link = document.getElementById("on");
document.body.style.backgroundColor= toggle ? '#ffffff' : '#000000';
link.innerHTML=toggle ? "Turn off the lights": "Turn on the lights";
link.style.color= toggle ? '#000000': "#00ffff";
toggle = !toggle;
}
</script>
You can toggle the settings based on a class value:
<a ... class="lightsOn" onclick="Lights(this);" ...>Turn off the lights</a>
then:
function lights(element) {
if (element.className == 'lightsOn') {
element.className = 'lightsOff';
// do settings for lights off
} else {
element.className = 'lightsOn';
// do settings for lights on
}
}
Most of the setting can be assigned to the class in CSS rather than hard coded in the function.
Note that function names starting with a capital letter are, by convention, reserved for constructors, and you shouldn't use an A element if you don't want an A, use a span with appropriate styling:
<style type="text/css">
.clickable {
cursor: pointer;
text-decoration: underline;
font-color: blue;
}
</style>
<span class="clickable" ...> ... </span>
Related
This question already has answers here:
How can I remove a style added with .css() function?
(21 answers)
Closed 3 years ago.
I have a button and it takes some styles with first click. But I want the user to be able to reset to the original with second click on own button or any button in page.
How can I do this?
my codes
$("#checkButton").click(function() {
$("#checkButton").css("color", "yellow");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="checkButton">name 1</button>
I think it is better to use a class and toggle that class using .toggleClass() in each button click.
.toggleClass() add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
$("#checkButton").click(function () {
$("#checkButton").toggleClass("colorClass");
});
.colorClass{
color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="checkButton">
name 1
</button>
You can do it with CSS styling, but I've made a below snippet in case if you want to change color without make CSS.
Check current color, and then set the different one.
$("#checkButton").click(function() {
var color = $("#checkButton").css("color")
var yellow = "rgb(255, 255, 0)"
if (color !== yellow) {
$("#checkButton").css("color", yellow);
} else {
$("#checkButton").css("color", "");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="checkButton">name 1</button>
Try this, It will work for you.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.my-class{
background-color: red;
color: yellow;
}
</style>
</head>
<body>
<button id="checkButton" class="">Click Me!</button>
<script>
$("button").click(function () {
$("#checkButton").toggleClass("my-class");
});
</script>
</body>
</html>
Create 4 buttons, each to modify a paragraph. Each button should turn on or off the changes to the paragraph on each click of the button.
1. Toggle bold button should bold the paragraph.
2. Toggle position should change the position of the paragraph
3. Toggle color will change the color
4. Toggle size will change the size.
My code till now:`
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Click the button to bold the text of the DIV element:</p>
<p><button onclick="myFunction()">Toggle Bold</button></p>
<div id="myDIV">Hello</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.innerHTML === "Hello") {
x.innerHTML = ;
} else {
x.innerHTML = "Hello";
}
}
</script>
</body>
</html>
Now, here I do not know how to change the paragraph text to bold in this. Moreover, I have to use the event handler for 4 buttons. How can I do it?
You can use the button to toggle the bold-ness of the paragraph by toggling the font-weight style.
function myFunction() {
var div = document.getElementById("myDIV");
if (div.style['font-weight']) {
div.style.removeProperty('font-weight');
} else {
div.style['font-weight'] = 800;
}
}
<p>Click the button to bold the text of the DIV element:</p>
<p><button onclick="myFunction()">Toggle Bold</button></p>
<div id="myDIV">Hello</div>
for the handling of four buttons with one function part you can do something like this.
as you create four buttons for each paragraph. modify the onclick event like
<p><button onclick="myFunction('myDiv')">Toggle Bold</button></p>
Here you are passing the ID of the paragraph controlled by the given button to the function
and modify the event handler with a div paramter like
function myFunction(asdf) {
var x = document.getElementById(asdf);
----your function----
}
I have an image of a gray star or blue star shown multiple times on the page. When I click on the gray star, it should change to blue. And when I click on the blue star, it should change to gray. Right now, when I click on one star, it changes all of them. How do I only change one image at a time?
This is in my root.html.erb
<img class="star-pic" src="/assets/star-gray.png">
This is in my javascript/application.js
$(document).ready(function(){
function changeStar(){
if($(".star-pic").attr("src") == "/assets/star-gray.png"){
$(".star-pic").attr("src", "/assets/star-blue.png")
}
else{
$(".star-pic").attr("src", "/assets/star-gray.png")
}
}
$(".star-pic").on("click", changeStar)
})
Any advice would be greatly appreciated. Thank you.
Inside your function changeStar() you are selecting all the images when any image is clicked and changing all of them as a result. Using $(this) selects the element that was clicked and changes it only.
$(document).ready(function() {
function changeStar() {
if ($(this).attr("src") == "/assets/star-gray.png") {
$(this).attr("src", "/assets/star-blue.png")
} else {
$(this).attr("src", "/assets/star-gray.png")
}
}
$(".star-pic").on("click", changeStar)
})
You are setting up your click event such that all .star-pic elements have their style modified when any are clicked because of this:
$(".star-pic").attr("src", "/assets/star-blue.png")
This changes the src attribute for all members of the JQuery wrapped set.
You only want to modify the one that was clicked so you should be writing:
$(this).attr("src", "/assets/star-blue.png")
to only affect the one that was clicked.
But, beyond that, your code can be dramatically reduced and the solution hugely simplified if you get rid of the img elements completely and just use div (or span) elements that have their background-image set via membership in a CSS class. Then, all you have to do it toggle that class membership.
$(function(){
function changeStar(){
// Use $(this) to get a reference to just the element being clicked as a JQuery object
// Simply toggle the use of the greyStar class to toggle the image shown
$(this).toggleClass("greyStar");
}
$(".star-pic").on("click", changeStar)
});
.star-pic {
width:50px;
height:50px;
background-size:cover;
/* All elements default to showing a blue star */
background-image:url("https://upload.wikimedia.org/wikipedia/commons/9/98/Human-emblem-star-blue-128.png");
display:inline-block;
}
/* But some elements are coded in the HTML to override blue and show grey from the start */
.greyStar {
background-image:url("http://www.dyson.com/airtreatment/humidifiers/am10/am10-white-silver/medialibrary/Reviews/Grey-star.ashx");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="star-pic greyStar"></span>
<span class="star-pic"></span>
<span class="star-pic greyStar"></span>
<span class="star-pic"></span>
<span class="star-pic greyStar"></span>
<span class="star-pic"></span>
You should could assign a click function at the star and change the corresponding star using 'this'
$(".star-pic").click(function (){
if($(this).attr("src") === "/assets/star-gray.png"){
$(this).attr("src", "/assets/star-blue.png")
}else{
$(this).attr("src", "/assets/star-gray.png")
}
}
You can use the following code.
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<img class="star-pic" src="/assets/star-gray.png">
<img class="star-pic" src="/assets/star-gray.png">
<img class="star-pic" src="/assets/star-gray.png">
<script>
$(document).ready(function(){
var clickedShape = $(this);
function changeStar(){
if($(this).attr("src") == "/assets/star-gray.png"){
$(this).attr("src", "/assets/star-blue.png")
}
else{
$(this).attr("src", "/assets/star-gray.png")
}
}
$(".star-pic").on("click", changeStar)
})
</script>
</body>
</html>
I am looking for javascript command that would do the following:
Click on image -> open spoiler
Click on image again -> hide spoiler
Here is what I got so far:
javascript in my html
<script>
function myFunction() {
document.getElementById("prvy").innerHTML = document.getElementById('spoiler_id').style.display='';}
</script>
Spoiler
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
And my button:
<div id="prvy" onclick="myFunction()"></div>
What I managed to do, is to click on a image, wich will open spoiler. Hovewer, I've been unable to do the second part, onclick again it will close the spoiler.
I also did serach for solution alredy, nothing worked for me, not even this: Link
I also tired if{} else{} statement but didn't work for me either.
Help would be really appreciated, as I am getting desperate on this one.
You can use jQuery .toggle() to toggle show/hide
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
Note : You need to include jQuery in your document as
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Working snippet :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
<div id="prvy" onclick="myFunction()">button</div>
<script>
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
</script>
In the JavaScript where you click the button use the simple jQuery function toggle.
$('#spoiler_id').toggle();
Toggle will hide the element selected if it is currently shown or display the element if it is currently hidden.
you would need some state that flips when the function is called.
like this.
<script>
var state = false;
function myFunction() {
state = !state;
if(state){
//do something
}else{
//do something else
}
}
</script>
Is that all of your code, it would be easier for you and less confusing too if you just gave the buttons an on click function and then called that function in your js.
Can I see all of your html
I am giving an example to concerned question using javascript.
HTML:
<script type="text/javascript">
var permit = 'true';
function showhide() {
var getcont = document.getElementsByClassName('hidshowcont');
if (permit === 'true') {
permit = 'false';
getcont[0].style.display = 'block';
}
else {
permit = 'true';
getcont[0].style.display = 'none';
}
}
</script>
<style type="text/css">
.hidshowcont{
height: 200px;
width: 300px;
border: 1px solid #333333;
display: none;
}
</style>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1cSDTn18ufwjuMihttTvCPJOnFY-4hxbPcaOVd87nSPaQakbP9IERaQ" />
<br />
<br />
<div class="hidshowcont">
This is an example of hide and show the container by clicking of an image.
</div>
This will help u much
I want my page to have two possible outcomes (50% chance) when page is refreshed/loaded. I know this has to be done with math random, but how?
Here is my current code for my 1st page outcome:
<html>
<head>
<title> Flow Test </title>
<script>
</script>
</head>
<body>
<h1>Some Flow of Control</h1>
<p>This text is a random combination of a foreground colour and background colour</p>
<p>In this case it's black on white</p>
<p> Signed </p>
<img src="bonw.gif">
</body>
</html>
This pages background will be white with black text. But for my second outcome I want it to have a black background with white text, and displaying the other image I have (wonb.gif).
How can this be done? If you know how it would be greatly appreciated, trying to get my head around this aspect of Javascript.
heres my jsfiddle: http://jsfiddle.net/sinead19/72s9wfgy/2/
You can use something like that. Using classes allows you to have multiple elements, with each having a random colour. Colours are defined in pure CSS.
<html>
<head>
<script>
window.addEventListener("load", function() {
var ps = document.getElementsByTagName("p");
for(var i = 0 ; i < ps.length ; i++) {
var p = ps[i];
if(p.classList.contains("randomColour")) {
p.classList.add("randomColour" + Math.ceil(Math.random() * 2));
}
}
});
</script>
<style>
.randomColour1 {
color: blue;
background-color: yellow;
}
.randomColour2 {
color: red;
background-color: black;
}
</style>
</head>
<body>
<h1>Some Flow of Control</h1>
<p class="randomColour">This text is a random combination of a foreground colour and background colour</p>
<p class="randomColour">This text is a random combination of a foreground colour and background colour</p>
<p class="randomColour">This text is a random combination of a foreground colour and background colour</p>
<p class="randomColour">This text is a random combination of a foreground colour and background colour</p>
<p>In this case it's black on white</p>
<p> Signed </p>
<img src="bonw.gif">
</body>
</html>
To add more colours, replace the 2 (after Math.random()) by the number of colours schemes, and add the required class in CSS.
Assuming not using JQuery, and you want an inline answer (changing styles on the JS page rather than calling a different CSS):
<html>
<title> Flow Test </title>
<body>
<p id="blackOrWhite" >This text is a random combination of a foreground colour and background colour</p>
<img id="image" src="bonw.gif">
<script>
//hide image by default
document.getElementById("image").style.display = "none";
if(Math.random() < 0.5){
document.getElementById("blackOrWhite").style.color = 'white';
document.body.style.backgroundColor = 'black';
document.getElementById("image").style.display = "inline";
} // Else is the default(white background color and a black text color)
</script>
</body>
</html>
All you really need here is a random toggle switch for two states.
Using the built-in Math.random() function to generate a random number between 0 and 1:
var toggle_state = ( Math.random() > 0.5? true: false );
If the generated number is more than 0.5 we'll set the boolean to true otherwise, false. In both cases, you would use the booleantoggle_state` in the same way:
var img_src = ( toggle_state? image_path1 : image_path2 );
document.getElementById( "image_holder" ).src = img_src;
document.body.style.backgroundColor = ( toggle_state? "black" : "white" );
Every time this code is executed it will check to see if the seconds value is an even/odd number and change the image source accordingly.
This code assumes that your <img> element has an id attribute of "image_holder".
Here is an inline demo:
var toggle_state = ( Math.random() > 0.5? true: false );
var img_src = ( toggle_state? "http://imgur.com/ovxadkg" : "http://imgur.com/TG2bbe5" ) + ".gif";
document.getElementById( "image_holder" ).src = img_src;
document.body.style.backgroundColor = ( toggle_state? "black" : "white" );
document.body.style.color = ( !toggle_state ? "black" : "white" );
<body>
<h1>Some Flow of Control</h1>
<p>This text is a random combination of a foreground colour and background colour</p>
<p>In this case it's black on white</p>
<p> Signed </p>
<img id="image_holder" src="bonw.gif" />
</body>
Complete html file structure for this fiddle: http://jsfiddle.net/ezzqqpcd/
<!DOCTYPE html>
<html>
<head>
<style>
.body1{
background: white;
color: black;
}
.body2{
background: black;
color: white;
}
</style>
</head>
<body>
<h1>Some Flow of Control</h1>
<p>This text is a random combination of a foreground colour and background colour</p>
<p>In this case it's black on white</p>
<p> Signed </p>
<img id="image" src="bonw.gif">
<script>
var rnd = Math.random();
if(rnd < 0.5)
document.querySelector("body").className = "body1";
else{
document.querySelector("body").className = "body2";
document.getElementById("image").src = "wonb.gif";
}
</script>
</body>
</html>
this code set's two different classes for the body and set's the classname two either one of them depending on a random number