How to append a method to my button? - javascript

I have a function called getRandomColor() and I want to apply this method to my button in the HTML doc. So, when you click the button it changes the entire body's color.
This is the javascript code:
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
This is the HTML code for the button and my attempt to apply the JS code:
<div class="row">
<div class="col-6-xs">
<button onclick="getRandomColor()"id="quotes"type="button" class="right-btn pull-right btn btn-success">Get Quotes</button>
</div>
Right away, I can tell that clicking the button won't change the document's color. I was thinking of adding this code to the getRandomColor() method:
document.body.style.background = color;
However, it still doesn't change the document color.

Actually the code you submitted, does seem to work, the only thing you might need to do is at the end of the function, apply the color to the DOM
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
document.body.style.background = color;
}
<body>
<div class="row">
<div class="col-6-xs">
<button onclick="getRandomColor()"id="quotes"type="button" class="right-btn pull-right btn btn-success">Get Quotes</button>
</div>
</div>
</body>

Related

Z-index in script [duplicate]

I made a website which consists of a display area that randomly spawns 50 circular <div> elements. I want to make it so when one of the circles is clicked, it comes to the foreground. I thought using the addEventListener function on each circle as it's created would work but I can't get it to do anything. Thank you.
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="index_styling.css">
<script type="text/javascript" src="index_scripts.js"></script>
</head>
<header>
<h1>First Last, Assignment #6</h1>
</header>
<div id="orange_strip"></div>
<body>
<form>
<ul>
<li>
<input type="button" name="add" value="Add Square">
<input type="button" name="change" value="Change All Square Colors">
<input type="button" name="reset" value="Reset All Squares">
</li>
</ul>
<div id="display">
</div>
</form>
</body>
<footer>
<div id="copyright">Copyright &copy 2016 - First Mid Last</div>
</footer>
</html>
JavaScript
window.onload = function() {
for (var i = 0; i < 50; i++) {
var display_div = document.getElementById("display");
var circle = document.createElement("div");
var randNum = getRandomDimension(5000);
circle.setAttribute("class", "circle");
circle.style.backgroundColor = getRandomColor();
circle.style.position = "absolute";
circle.style.left = getRandomDimension(550);
circle.style.top = getRandomDimension(450);
circle.addEventListener("click", bringToFront(circle));
display.appendChild(circle);
}
}
function bringToFront(element) {
element.style.zIndex = "1";
}
function getRandomColor() {
var letters = "0123456789abcdef";
var result = "#";
for (var i = 0; i < 6; i++) {
result += letters.charAt(parseInt(Math.random() * letters.length));
}
return result;
}
function getRandomDimension(max) {
var num = Math.floor((Math.random() * max) + 1);
var str = num.toString();
return str += "px";
}
This line:
circle.addEventListener("click", bringToFront(circle));
...does not add an event listener. It calls your bringToFront() method immediately and then attempts to assign its return value as a listener except the return value is undefined. (Meanwhile, the effect of calling that function immediately within the loop means all of your divs get set to z-index: 1 upon their creation.)
You should be passing a reference to the function (note there is no () after the function name):
circle.addEventListener("click", bringToFront);
...and then change the function to work with this, because this will automatically be set to the clicked element at the time the function is called for the event:
function bringToFront() {
this.style.zIndex = "1";
}
The problem is with the current line
circle.addEventListener("click", bringToFront(circle));
That is trying to execute the bringToFront function right away.
AddEventListener just needs to function, and it will execute it when the event fires
circle.addEventListener("click", bringToFront);

How to apply class function on id function?

So I have a task to make function (show/hide) for every paragraph (five of them) and I did like so
function btn() {
var x = document.getElementById('para');
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
For every paragraph I used Id instead of class. Because task said one button per one paragraph.
Now I have a problem how to apply this (color) function for all of them in the same time.
function color() {
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
elements = document.getElementByClassName('color');
for (var i = 0; i < elements.length; i++) {
document.getElementByClassName('color')[i].style.backgroundColor = bgColorCode;
}
}
//Html
<button onclick = "color()">Color</button>
<button onclick = "btn()">Show/Hide</button>
<p id = "para"> Example 1 </p>
<button onclick = "btn2()">Show/Hide</button>
<p id = "para2"> Example 2 </p>
...
Idk how to apply this function "color" to all of my paragraphs because they are under id?
Any solutions?
If you add the class color to your para elements and change the function getElementByClassName() to getElementsByClassName() (you forgot an s). then your code works. Within the for loop you can use the elements array elements[i] instead of another call to the getElementsByClassName() function.
function color() {
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
elements = document.getElementsByClassName('color');
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = bgColorCode;
}
}
//just slightly modified so it works with multiple paragraphs by making the id a function parameter.
function btn(id) {
var x = document.getElementById(id);
if (x.style.display == "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="color()">Color</button>
<button onclick="btn('para')">Show/Hide</button>
<p class="color" id="para">Example 1</p>
<button onclick="btn('para2')">Show/Hide</button>
<p class="color" id="para2">Example 2</p>
Hope this is what you want. Tell me if you have doubts.
The function toggleshow(htmlObj) selects next element sibling of element which triggered the function with an argument this which represent the current HTMLelement and if the value of style.display is set to none, then it changes it value to block else change it to none.
see HTML DOM manipulation
The second function color() takes advanced parameters that is (string)id of HTML element, and loops through all arguments passed and change bgcolor for every id. You can pass many arguments as you want.
see this
document.querySelector('css selector') selects first html element using css selectors
function toggleshow(htmlObj){
var par = htmlObj.nextElementSibling;
if(par.style.display !== 'none'){
par.style.display = 'none';
}else{
par.style.display = 'block';
}
}
function color(){
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
for (var i = 0; i < arguments.length; i++) {
document.querySelector('#'+arguments[i]).style.backgroundColor = bgColorCode;
}
}
button{
display:block
}
<button onclick = "color('para', 'para2', 'para3', 'para4', 'para5')">Color</button>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para"> Example 1 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para2"> Example 2 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para3"> Example 2 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para4"> Example 2 </p>
<button onclick = "toggleshow(this)">Show/Hide</button>
<p id = "para5"> Example 2 </p>
*sorry for my bad English and spelling mistakes.
A better and more dynamic solutions with JQUERY:
*If you don't know how to use Jquery then you can check Mark Baijens answer.
function btn(e) {
if ($(e).next().css('display') == "none") {
$(e).next().show()
$(e).html("Hide")
} else {
$(e).next().hide()
$(e).html("Show")
}
}
function color() {
bgColorCode = '#' + Math.floor((Math.random() * 999999) + 100000);
//elements = document.getElementByClassName('color');
$(".para").css("background-color",bgColorCode)
}
<div>
<button onclick = "color()">Color</button>
</div>
<hr>
<div id="wrapper">
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 1 </p>
<hr>
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 2 </p>
<hr>
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 3 </p>
<hr>
<button onclick = "btn(this)">Show/Hide</button>
<p class="para"> Example 4 </p>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

animate elements in random sequence

I try to animate some buttons. A random string should be generated that the animated buttons arent always in the same sequence. fiddle
an example:
text = 1423
the first animated button is btn1 then after one second btn4 then after one second btn2 then after one second btn3
the buttons:
<div>
<button name="btn1" type="submit" id="btn1" value="1" style="" class="button"></button>
<button name="btn2" type="submit" id="btn2" value="2" style="" class="button"></button>
</div>
<div>
<button name="btn3" type="submit" id="btn3" value="3" style="" class="button"></button>
<button name="btn4" type="submit" id="btn4" value="4" style="" class="button"></button>
</div>
the javascript:
var textArray = [];
var text = "";
function makeid()
{
var possible = "1234";
for( var i=0; i < 4; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
makeid();
textArray = text.split("");
console.log(textArray);
function animate1() {
$('#btn' + textArray[0]).animate( { backgroundColor: 'red' }, 500);
}
function animate2() {
$('#btn' + textArray[1]).animate( { backgroundColor: 'red' }, 500);
}
function animate3() {
$('#btn' + textArray[2]).animate( { backgroundColor: 'red' }, 500);
}
function animate4() {
$('#btn' + textArray[3]).animate( { backgroundColor: 'red' }, 500);
}
window.setTimeout(animate1, 1000);
window.setTimeout(animate2, 2000);
window.setTimeout(animate3, 3000);
window.setTimeout(animate4, 4000);
Your issue about shuffling the possible text, because in your function there is a possibility that same number repeated. like: 2,2,2,1 or 4,4,4,4 and so on.
you can use this shuffle function instead of your method of shuffling:
function shuffleWord(word) {
var shuffledWord = '';
var charIndex = 0;
word = word.split('');
while (word.length > 0) {
charIndex = word.length * Math.random() << 0;
shuffledWord += word[charIndex];
word.splice(charIndex, 1);
}
return shuffledWord;
}
See JsFiddle of your example after updates.
You can't animate backgroundColor unless the jQuery.Color plugin is used, jQuery animate docs
All animated properties should be animated to a single numeric value,
except as noted below; most properties that are non-numeric cannot be
animated using basic jQuery functionality (For example, width, height,
or left can be animated but background-color cannot be, unless the
jQuery.Color plugin is used).
And you allow duplicate IDs when creating the random order. Also, the code can be simplified.
var textArray = [];
function makeid() {
var num;
var possible = "1234";
while(textArray.length < 4) {
num = possible.charAt(Math.floor(Math.random() * possible.length));
if (textArray.indexOf(num) === -1) {
textArray.push(num)
}
}
}
function animate(id, wait) {
setTimeout(function() {
$('#btn' + id).animate({ width: '200'}, 500);
}, wait);
}
makeid();
for (var i=0; i < textArray.length; i++) {
animate(textArray[i], i * 1000)
}
fiddle

Rainbow Scrolling Text Using <span>

I would like to turn a small paragraph into rainbow text, in which the colors scroll from right to left in an infinite loop using JavaScript. I currently have this paragraph:
<div id="rainbow">
<p id="rtext">
<span id="s1" style="color: red">H</span>
<span id="s2" style="color: blue">e</span>
<span id="s3" style="color: green">l</span>
<span id="s4" style="color: purple">l</span>
<span id="s5" style="color: orange">o</span>
<span id="s6" style="color: magenta">!</span>
</p>
</div>
<div id="actbtn">
<button onclick="activ()">Click for RAINBOW!</button>
</div>`
I am fairly new to JavaScript so I am not sure how to write the activ() function to infinitely scroll the colors.
EDIT:
I would like to thank Ben for the looping script, but now I also need to know how to use the activ() function to change the color of a <span> element. I have tried the following script:
function activ() {
document.getElementById("s1").style.color = 'magenta';
}
But the color will not change. I am trying to keep the script as simple as possible, but also make it work.
FINAL EDIT:
I used Ivan's "UPD Without JQuery" code and added a few colors, and this is what I end up with:
<script>
function EyeVommit() {
document.getElementById("actbtn").style.display = 'none';
'use strict';
var colors = ['red', 'blue', 'green', 'purple', 'orange', 'magenta', 'chartreuse', 'cyan', 'yellow'],
target = document.getElementById('rtext').children,
i,
len = colors.length,
inter = setInterval(function() {
colors.unshift(colors.pop());
for (i = 0; i < len; i++) {
target[i].style.color = colors[i];
}
}, 200);
}
</script>
<div id="table1">
<p id="rtext"> <span id="s1">H</span><span id="s2">e</span><span id="s3">l</span><span id="s4">l</span><span id="s5">o</span><span id="s6">!</span>
<br />
<div id="actbtn">
<button onclick="EyeVommit()">Pabam!</button>
</div>
</p>
The result.
I'm begging you, never, never, never use it in design
<html>
<head>
<title>Price</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script>
function EyeVommit() {
'use strict';
var colors = ['red', 'blue', 'green', 'purple', 'orange', 'magenta'],
$target = $('#rtext span'),
counter,
i,
len = colors.length,
inter;
for (i = 0; i < len; i++) {
$target[i] = $($target[i]);
}
inter = setInterval(function () {
colors.unshift(colors.pop());
for (i = 0; i < len; i++) {
$target[i].css('color', colors[i]);
}
}, 200);
}
</script>
<div id="table1">
<p id="rtext">
<span id="s1">H</span>
<span id="s2">e</span>
<span id="s3">l</span>
<span id="s4">l</span>
<span id="s5">o</span>
<span id="s6">!</span>
</p>
</div>
<script>
EyeVommit();
</script>
</body>
</html>
UPD without jQuery
<script>
function EyeVommit() {
'use strict';
var colors = ['red', 'blue', 'green', 'purple', 'orange', 'magenta'],
target = document.getElementById('rtext').children,
i,
len = colors.length,
inter = setInterval(function () {
colors.unshift(colors.pop());
for (i = 0; i < len; i++) {
target[i].style.color = colors[i];
}
}, 200);
}
</script>
<div id="table1">
<p id="rtext">
<span id="s1">H</span><span id="s2">e</span><span id="s3">l</span><span id="s4">l</span><span id="s5">o</span><span id="s6">!</span>
<button onclick="EyeVommit()">Pabam!</button>
</p>
</div>
If by "Infinitely scroll" you mean create an infinite loop, you could do this.
function blaah(blaah){
//This is where you put all of your rainbow-y code
blaah("blaah");
}
Then you can just call the event through your button.
This code works because everytime the function runs, you call it again. (Second-last line of the function.)
Here's one that will work for any text that you put in the rtext block
Here is a codepen: http://codepen.io/anon/pen/GtwxD
Here's the HTML
<div id="rainbow">
<p id="rtext">Hello! This is some rainbow text!</p>
</div>
<div id="actbtn">
<button>Click for RAINBOW!</button>
</div>
This is the Javascript
$(document).ready(function(){
createSpans();
$('#actbtn').click(activ);
});
$rtxt = $('#rtext');
var text = $rtxt.html() , color;
function createSpans(){
$rtxt.html(' ');
window.colorCount = 0;
window.on = false;
colorPicker();
}
function activ(){
if(!window.on){
window.id = setInterval(colorPicker,100);
window.on = true;
}
else{
clearInterval(window.id);
window.on = false;
}
}
function colorPicker(){
$rtxt.html(' ');
window.colorCount++;
for(var letter = 0; letter < text.length; letter++){
switch ((letter + colorCount) % 6){
case 0 :
color = "red";
break;
case 1 :
color = "orange";
break;
case 2:
color = "green";
break;
case 3 :
color = "purple";
break;
case 4 :
color = "blue";
break;
case 5 :
color = "gold";
break;
default :
color = "black";
break;
}
$rtxt.append('<span style=" color:' + color + ';">' + text[letter] + '</span>');
}
}

Have html show up after javascript function completes

I'm attempting to create a generic game of blackjack through javascript. The game starts when you click the start button:
<button type="button" onClick="deal()">Start Game</button>
which in turn runs the method deal:
function deal() {
card1 = Math.floor(Math.random() * 52);
card2 = Math.floor(Math.random() * 52);
card1 = changeCard(card1);
card2 = changeCard(card2);
score = card1 + card2;
for (var i = 0; i < aceAmount || score > 21;aceAmount--) {
score -= 10;
}
document.write("You were dealt a " + card1 + " and a " + card2 + " for a total of " + score + ".\nDo you wish to hit or pass?");
aceAmount = 0;
};
My question is once the deal method runs, how can I get two html buttons to show up on the screen, such as:
<button type="button" onClick="hit()">Hit</button>
<button type="button" onClick="pass()">Pass</button>
What to do?
Use the CSS display property to hide your buttons, then using the getElementById, method you "select" those buttons to do some "Javascripty" stuff on them.
Your HTML
<button id="hit_btn" style="display:none;" type="button" onClick="hit()">Hit</button>
<button id="pass_btn" style="display:none;" type="button" onClick="pass()">Pass</button>
and add this to your Javascript function:
document.getElementById('hit_btn').style.display = '';
document.getElementById('pass_btn').style.display = '';
and when you want to hide them back again
document.getElementById('hit_btn').style.display = 'none';
document.getElementById('pass_btn').style.display = 'none';
you could set an id or class on the buttons, and set a css rule with display:none. At the end of the deal function, set a line which changes display to block or inline. in jQuery, it would be
$('button.hit').css({visibility: "visible"})

Categories

Resources