Javascript Background Change Colour - javascript

I am trying to learn Javascript on my own. So I gave myself a task: Create a button and with that button I can change the background colour. This is what I have done so far. I assume I don't need to run it under localhost like how we usually do PHP? I only drag the file to Google Chrome. So far, after clicking, it doesnt change colour at all. I also wonder why. Would be grateful if someone could point out my error
exe1.html
<html>
<head>
<link rel="stylesheet" href="layout.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
$('body').css('background', '#' + changeColour());
});
});
function changeColour() {
return Math.floor(Math.random()*16777215).toString(16);
}
</script>
</head>
<body>
<div class="buttonClickMe">
<button type="button" onclick="changeColour">Click me</button>
</div>
</body>
layout.css
button
{
background-color: red;
width: 100px;
height: 100px;
}
body
{
text-align: center;
background-color: blue;
}

Looks like you are trying to implement the click event in two ways:
as a HTML attribute
<button type="button" onclick="changeColour">
In order for this way to work, you should use changeColour as a function:
<button type="button" onclick="changeColour()">
via JS
$('.button').click(function(){ ...
This is the wrong selector for button (the . looks for elements by class name). Instead, use button:
$('button').click(function(){ ...
Either method will work and you only need one.

This should work
$(document).ready(function () {
$('.button').click(function () {
changeColour();
});
});
function changeColour() {
var col = Math.floor(Math.random() * 16777215).toString(16);
$('body').css('background', '#' + col);
}

If you are learning javascript don't jump so fast to jQuery, first do it in plain javascript, like this.
Pure JS
var array = ['black','red','yellow']; //create an array with colors
function changes(){ //create the function
document.bgColor= array[Math.floor(Math.random()* array.length)]; //change the document. for example
}
HTML
<button type="button" onclick="change()">Click me</button>

The selector you're using for the click event does not exist. Add a class to the button for it t work.
Try this:
HTML
<button type="button" class="button">Click me</button>
CSS
$(document).ready(function(){
$('.button').on('click', function(){
$('body').css('background', '#' + changeColour());
});
});
function changeColour() {
return Math.floor(Math.random()*16777215).toString(16);
}

What you've done is fine,
You should move the button class .button onto the actual button element and remove the onclick and then should work.
Here:
http://jsfiddle.net/745ex5zc/

$('.button').click(function(){...
is referring to a click on a button with the CLASS button.
Simply add class=""button" to your button and it would work, though I'd recommend using id="myId" and using $('#myId').click(function(){ instead.

Give this a try...
JSFiddle https://jsfiddle.net/w6tjtaqy/
<script>
$(document).ready(function(){
$('.button').click(function(){
$('body').css('background', '#' + changeColour());
});
});
function changeColour() {
return Math.floor(Math.random()*16777215).toString(16);
}
</script>
<style>
button
{
background-color: red;
width: 100px;
height: 100px;
}
body
{
text-align: center;
background-color: blue;
}
</style>
<div class="buttonClickMe">
<button type="button" class="button">Click me</button>
</div>

Related

Change a style then with second click reset to original class [duplicate]

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>

How to get event target/this without putting the event listener in the HTML tag? [duplicate]

This question already has answers here:
Get clicked element using jQuery on event?
(6 answers)
Closed 5 years ago.
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use
$(document).ready(function(){})
I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?
//$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>
Thanks in advance!
PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.
PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D
PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)
Firstly you need to define function() in a click function so it should look like this:
$("button").click(function() {
//code to execute here
});
Instead of this:
$("button").click(//code to execute here);
When calling this in a button it will refer to the button and if I understand your code right, the image is hidden therefore if that is the button then you can't click a hidden image, if you're using a separate button to hide the image then in the click function you need to have e stated as the image element.
To use this you also need to call it as $(this) not just this.
This should work.
//$(document).ready(function() {
window.onload = startup();
function startup() {
console.log("window loaded");
$("img").hide();
$("button").click(function() {showImage(this)});
}
function showImage(e) {
console.log("onside eras");
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
this will be set inside the event handler as event.currentTarget Ref. If you are using jQuery you can make a jQuery object from it by doing $(this). So to get the value you can do:
var chosen = $(this).prop('value');
I have also added a class myclass to the buttons to select it using $('.myclass') so that this can be seperated from other possible buttons in the page. You can also do $('button') instead to select all buttons irrespective of the class.
UPDATE
Just saw your commented out code:
$("button").click(showImage(this)); // When a button is clicked
// call the function returned by showImage(this).. err it doesnt return
// a function so it fails.
you should pass a function reference or simply a function name to the click event registration. like .click(showImage) without any function call (). In your code it will execute showImage(this) and bind the returned value to the event listener, which will apparently fail.
It should actually be:
$("button").click(showImage); // when a button is clicked
// call the function showImage with this=<clicked button> and param=event
and this will be automatically set inside the function as event.currentTarget
$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = $(this).prop('value');
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
$('.myclass').on('click', showImage);
});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" class="myclass">Gris</button>
<button value="cow" class="myclass">Ku</button>
<button value="sheep" class="myclass">Sau</button>
<button value="hen" class="myclass">Høne</button>

Click button to show div, then remove button

I have managed to create a button that shows my div. but I want to have the button disappear as that happens.
At the moment my button only disappears the second time I click it. Any help appreciated.
$(document).ready(function() {
$('.click').click(function() {
$('#contact-form').toggle('slide', 500)
$('.click').toggle();
});
});
.click {
display: block;
}
#contact-form {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click">click</button>
<div id="contact-form"></div>
The reason why it is not working is, you are mixing the display between CSS and JavaScript. jQuery uses the current inline style to check if the button is hidden to display it, when you use .toggle(). Since it doesn't have anything at first, it adds a display: block (or whatever the initial value is) and then when you do the second time, it correctly identifies and removes.
The best thing to do is to use classes. I would suggest something like this parent class.
$(document).ready(function() {
$('.click').click(function() {
$("body").toggleClass("contact-form-open");
});
});
.contact-form-open .click,
#contact-form {
display: none;
}
.contact-form-open #contact-form {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click">Click Me</button>
<div id="contact-form">
Contact Form
</div>
This way, you control everything using CSS and you don't mess up with the event listeners or add the yucky inline CSS.
I've tried what you've tried and it seems to be working. Maybe it's because you don't close the div tag ?
$(function() {
$('.click').click(function() {
$('.myDiv').toggle();
$('.click').toggle();
})
});
http://plnkr.co/edit/wD0bwf8XK3CFXXM7rVWF?p=preview
but I want to have the button disappear as that happens.
So just use hide() instead of toggle :
$('.click').click(function() {
$('.click').hide();
$('#contact-form').toggle('slide', 500)
});
Hope this helps.
$(document).ready(function() {
$('.click').click(function() {
$('.click').hide();
$('#contact-form').toggle('slide', 500)
});
});
#contact-form {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click">click</button>
<div id="contact-form">Form content</div>
More easy:
$(document).ready(function() {
$('.click').click(function() {
$("#contact-form").show();
$(this).remove();
});
});
#contact-form{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click">Click Me</button>
<div id="contact-form">
Contact Form
</div>

javascript - one image,two actions

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

inserting divs with javascript

i have the following code that i was hoping would allow me to click a button and add another box to the page but inj stread it just resets the page every time i click one of the buttons
<style>
div.box
{
width: 50px;
height: 50px;
background-image: url("Images/smallBox.jpg");
}
div.largeBox
{
width: 100px;
height: 100px;
background-image: url("Images/largeBox.jpg");
}
</style>
<script type="text/javascript">
$(function () {
setupDragging();
});
function setupDragging() {
$(".box").draggable({ snap: true });
$(".largeBox").draggable({ snap: true });
}
function addSmallBox() {
var boxArea = document.getElementById('boxArea');
var newBox = document.createElement('div');
newBox.setAttribute('class', 'box');
boxArea.appendChild(newBox);
setupDragging();
}
function addLargeBox() {
var boxArea = document.getElementById('boxArea');
var newBox = document.createElement('div');
newBox.setAttribute('class', 'largeBox');
boxArea.appendChild(newBox);
setupDragging();
}
</script>
<form>
<button onclick="addSmallBox();">small box</button>
<button onclick="addLargeBox();">large box</button>
</form>
<div id="boxArea">
</div>
please can somebody let me know what i am doing wrong and how i can achieve what i want.
ANSWER:
just an update on the final result
<style>
div.box
{
width: 50px;
height: 50px;
background-image: url("../Images/smallBox.jpg");
position: absolute;
}
div.largeBox
{
width: 100px;
height: 100px;
background-image: url("../Images/largeBox.jpg");
position: absolute;
}
</style>
<script type="text/javascript">
$(function () {
setupDragging();
$('.addBox').click(function(e){
if($(this).hasClass('smallBox')) addSmallBox();
else if($(this).hasClass('largeBox')) addLargeBox();
e.preventDefault();
})
});
function setupDragging() {
$(".box").draggable({ snap: true });
$(".largeBox").draggable({ snap: true });
}
function addSmallBox() {
$('<div>', { class: 'box' }).appendTo('#boxArea')
setupDragging();
}
function addLargeBox() {
$('<div>', { class: 'largeBox' }).appendTo('#boxArea')
setupDragging();
}
</script>
<form>
<button class='addBox smallBox'>small box</button>
<button class='addBox largeBox'>large box</button>
</form>
<div id="boxArea">
</div>
i made use of several of the answers below and this was the final result but went down the html5 route in the end.
First of all, since you are using jQuery, if I were you, I would not use the onclick attribute in your button. Instead, add an event listener like so:
$('button').click(function(){
addLargeBox();
return false;
});
OR
$('button').click(function(e){
addLargeBox();
e.preventDefault();
});
Both of which will prevent the user's browser from following the link but will execute the JavaScript as you want.
Also, since you require two different functions to be executed depending on which button is clicked, you should probably add a class or id to differentiate the two.
Your markup would then look like this:
<button class="add-box">small box</button>
<button class="add-box large-box">large box</button>
And your JavaScript would be:
$('.add-box').click(function(){
if ($(this).hasClass('large-box')) addLargeBox();
else addSmallBox();
return false;
});
The button tag you are using is a HTML5 version of a form submit button which causes a page refresh.
Change the buttons to:
<input type="button" onclick="addSmallBox();" value="small box" />
Or put return false at the bottom of each of your javascript functions.
Couple of things:
Always separate JS from code (that means lose the onclick attributes and bind them in javascript instead.)
The form is still being submitted; have your functions return false/preventDefault (jQuery) to avoid this.
Some hints:
Since you're already using jQuery, why not build html elements with it? ($('<div>',{class:'box'}).appendTo('#boxArea') for instance)
You have to return false from the click event to prevent the default browser behavior of following the link.
I'm not sure why just by glancing at the code, but perhaps you could try retrieving the boxArea.InnerHTML, appending the appropriate HTML string to it, and setting the boxArea.InnerHTML to the result.
Something like:
boxArea.InnerHTML = boxArea.InnerHTML + "<div class='largeBox'></div>";

Categories