I need a button which can change the background color if you click it 2x.
How can I do this?, I only know how to do it with 1 click.
My code is actually this:
<button onClick="document.body.style.backgroundColor ='#000';"> color </button>
Use onDblClick instead:
<button onDblClick="document.body.style.backgroundColor ='#000';"> color </button>
You can store the number of clicks in a variable and add a click event listener to the button that increments the counter and checks whether it is 2, and if so, sets the background color of the body.
var clicks = 0;
btn.addEventListener('click', function(){
if(++clicks == 2){
document.body.style.backgroundColor ='#000';
}
})
<button id="btn"> color </button>
Similar to the response of #Spectric, store the number of clicks in a variable and add a click event listener to the button.
I don't know logic is what is desired.
You could add another button with an idea equal to the one placed, but in reverse: subtracting.
const btnEle = document.querySelector(".btn");
const resEle = document.querySelector(".result");
const legendEle = document.querySelector("#legend");
let clickCount = 0;
btnEle.addEventListener("click", () => {
clickCount++;
resEle.innerHTML = "The button has been clicked " + clickCount + " times ";
if (clickCount > 1) {
document.body.style.backgroundColor ='#000';
legendEle.style.color = '#1E5128';
}
});
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
<div class="result"></div>
<br />
<button class="btn">CLICK HERE</button>
<h3 id="legend">Click on the above button to check if the button is clicked</h3>
<input type="button" id="btn" onclick="eventB()">
function eventB() {
var click = 0;
btn.addEventListner('click', function() {
if(++click == 2){
window.document.body.style.background = '##836fff';
}
})
Related
The problem: I am not able to get the value of the HTML list from javascript. Each time user click next button, the program will count how many times the user clicks the next button. In javascript, I called the HTML list and iterate it. inside for loop, I called user click on next button number and add 1, The result of the sum will go inside the array and display that array line data. I don't know because of some reason I can't able to get data. Let me know if you get confused
Here is the HTML code
<div id="Border" class="">
<div id="Topic_List" class="creature">
<ul id="ListName" class="">
<li> Google </li>
<li>Facebook</li>
<li> Google </li>
</ul>
</div>
</div>
<div id="" class="" style="clear:both;"></div>
<div id="InputInsideFullCover" class="">
<textarea id="File_Name" name="File_Name"></textarea>
</div>
<button id="clickme" onclick="Next()"> Next </button>
<button onclick="Prev()"> Prev </button>
Here is the JavaScript code
<script>
function Next(){
var button = document.getElementById("clickme"),
count = 0;
button.onclick = function() {
count += 1;
var ul = document.getElementById("ListName");
var items = ul.getElementsByTagName("li");
for (var i = 0; i < items.length; ++i) {
var GetButtonClickValue = count;
var AddOne = GetButtonClickValue + 1;
var file_name = document.getElementById("ListName").innnerHTML=items[AddOne];
document.getElementById("File_Name").href = file_name;
var url_to_file = "http://www.example.com/"+file_name;
$.ajax({
url: url_to_file,
type:'HEAD',
error: function()
{
alert('data not found.');
},
success: function()
{
}
});
}
if(count > 9){
count = " ";
count = 1;
button.innerHTML = "Click me: " + count;
}
};
}
</script>
here is the CSS code
<style>
#Border{margin:5px auto;padding:0;width:50px;height:auto;border:1px solid #666;background-color:#f1f1f1}
#InputInsideFullCover{margin:5px;padding:0;width:700px;height:auto;}
#File_Name{margin:0;padding:0;width:638px;height:25px;resize:none;}
#Topic_List{margin:5px;padding:0;width:640px;height:auto;}
#Topic_List ul{margin:0px;padding:0;height:auto;width:12px;}
#Topic_List li{margin:0px;padding:0;list-style-type:none;float:left}
#button{
background-color: #4CAF50; /* Green background */
border: 1px solid green; /* Green border */
color: white; /* White text */
padding: 10px 24px; /* Some padding */
cursor: pointer; /* Pointer/hand icon */
width: 50%; /* Set a width if needed */
display: block; /* Make the buttons appear below each other */
}
.btn-group button:not(:last-child) {
border-bottom: none; /* Prevent double borders */
}
/* Add a background color on hover */
.btn-group button:hover {
background-color: #3e8e41;
}
</style>
You are declaring count to 0 at the beginning of the function. So every time the button is clicked count equals 0 and then one is added. (It will always be 1) You need to pull the count var outside of the function. This will also be useful for your Prev function. I bet that your Next and prev functions will be similar enough to make only one function. Call your function with true or false to add or subtract the count.
Just Add this
<script src="jquery-3.4.0.min.js"></script>
in your head tag before the external script tag
beacuse you are using ajax you need jquery
So, I'm wondering if i can make this any simpler (less repetition in the javascript) and whether or not I can make it so the title only turns black when hitting a button if it is that buttons color. If the second part of the question is possible it doesn't need to be simpler I'm just trying to figure out how to make the function target only tags with a specific attribute (style). Is this possible?
I'm new to coding I've been trying to figure this out for a few hours and can't find something already uploaded... possibly due to my lack of being able to condense the question.
<!DOCTYPE html>
<html>
<head>
<title>
Flood
</title>
<link rel="stylesheet" href="Style.css">
<style>
h1 {
text-align: center;
padding-left: 30%;
padding-right: 30%;
width: 40%;
}
p {
font-size: 14pt
}
</style>
</head>
<body>
<section class="mainpage">
<h1 id="FS"> Fun Stuff </h1>
<div>
<button id="Red"> Red</button>
<button id="Blue"> Blue</button>
<button id="Yellow"> Yellow</button>
<button id="Blink"> Blink</button>
</div>
<div id="explaination">
<p>Click the buttons at the top to see what I mean.
</p>
</div>
</section>
<script>
const a = document.getElementById("FS");
const b = document.getElementById("Red");
const c = document.getElementById("Blue");
const d = document.getElementById("Yellow");
const e = document.getElementById("Blink");
/*reset Functions*/
function blackFunctionB() {
a.style.color = "black";
b.removeEventListener("click", blackFunctionB,);
b.addEventListener("click", redFunction,);
}
function blackFunctionC() {
a.style.color = "black";
c.removeEventListener("click", blackFunctionC,);
c.addEventListener("click", blueFunction,);
}
function blackFunctionD() {
a.style.color = "black";
d.removeEventListener("click", blackFunctionD,);
d.addEventListener("click", yellowFunction,);
}
function showFunction() {
a.style.display = "block";
e.removeEventListener("click", showFunction,);
e.addEventListener("click", blinkFunction,)
}
/*end reset functions*/
b.addEventListener("click", redFunction,);
function redFunction() {
a.style.color = "Red";
b.removeEventListener("click", redFunction,);
b.addEventListener("click", blackFunctionB,);
}
c.addEventListener("click", blueFunction,);
function blueFunction() {
a.style.color = "Blue";
c.removeEventListener("click", blueFunction,);
c.addEventListener("click", blackFunctionC,);
}
d.addEventListener("click", yellowFunction,);
function yellowFunction() {
a.style.color = "Yellow";
d.removeEventListener("click", yellowFunction,);
d.addEventListener("click", blackFunctionD,);
}
e.addEventListener("click", blinkFunction,);
function blinkFunction() {
a.style.display = "none"
e.removeEventListener("click", blinkFunction,);
e.addEventListener("click", showFunction,);
}
</script>
</body>
So basically when you click on the yellow button it makes the block turn yellow, then if you hit the blue button it makes it blue, but if you hit the yellow button again it makes it black. Alternatively, when you hit the yellow then blue twice then yellow again it stays black. Is there a way to make it only turn black if you hit the yellow button when it is already yellow?
You could make one function that is more generic and can handle all the cases you have:
function toggleCss(elem, attrib, value) {
elem.style[attrib] = elem.style[attrib] === value ? "" : value;
}
const fs = document.getElementById("FS");
for (let color of ["red", "blue", "yellow"]) {
const button = document.getElementById(color);
button.addEventListener("click", () => toggleCss(fs, "color", color));
}
const button = document.getElementById("blink");
button.addEventListener("click", () => toggleCss(fs, "visibility", "hidden"));
<section class="mainpage">
<h1 id="FS"> Fun Stuff </h1>
<div>
<button id="red"> Red </button>
<button id="blue"> Blue </button>
<button id="yellow"> Yellow </button>
<button id="blink"> Blink </button>
</div>
<div id="explanation">
<p>Click the buttons at the top to see what I mean.</p>
</div>
</section>
You could even make it more generic by defining data attributes on the buttons which indicate which CSS property needs to toggle:
function toggleCss(elem, attrib, value) {
elem.style[attrib] = elem.style[attrib] === value ? "" : value;
}
const fs = document.getElementById("FS");
for (const button of document.querySelectorAll("button[data-attr]")) {
button.addEventListener("click", () =>
toggleCss(fs, button.dataset.attr, button.dataset.value)
);
}
<section class="mainpage">
<h1 id="FS"> Fun Stuff </h1>
<div>
<button data-attr="color" data-value="red">Red</button>
<button data-attr="color" data-value="blue">Blue</button>
<button data-attr="color" data-value="yellow">Yellow</button>
<button data-attr="visibility" data-value="hidden">Blink</button>
</div>
<div id="explanation">
<p>Click the buttons at the top to see what I mean.</p>
</div>
</section>
You are over complicating things. Simply check and toggle the black and 2nd color.
You don't have to register/de-register events again and again.
function yellowFunction() {
var clr = a.style.color;
if(clr.toLowerCase() === 'yellow')
a.style.color = "black";
else
a.style.color = "Yellow";
}
my problem is pretty simple. I'm trying to switch 2 elements id by clicking either of them using only vanilla JavaScript.
It works on the first click to use the correct CSS for the new id, but afterward, it does not seem to recognize click events to the new id. Here is a short code example to illustrate this:
document.addEventListener("DOMContentLoaded", function(){
var blueSpin = document.getElementById("blue-spinner");
var orangeSpin = document.getElementById("orange-spinner");
blueSpin.addEventListener("click", function() {
document.getElementById("h1").innerHTML = "You've Clicked Blue";
blueSpin.setAttribute("id","orange-spinner");
orangeSpin.setAttribute("id", "blue-spinner")
});
orangeSpin.addEventListener("click", function() {
document.getElementById("h1").innerHTML = "You've Clicked Orange";
orangeSpin.setAttribute("id", "blue-spinner");
blueSpin.setAttribute("id", "orange-spinner");
});
});
h1, h2 {
font-weight: bold;
text-align: center;
font-size: 45px;
font-family: 'VT323', monospace;
margin: 15px;
}
#blue-spinner {
color: blue;
}
#orange-spinner {
color: goldenrod;
}
<script src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"></script>
<html>
<body>
<h1 id="h1">Click Something:</h1>
<h2 id="blue-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
<h2 id="orange-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
</body>
</html>
My expectation is that upon clicking either spinner, the colors will switch, and the header will identify which one was clicked before the change. After that, you should be able to click either of the spinners with the same result.
Any help anyone can provide would be appreciated! Happy X-mas Eve Eve!
I would use class selectors in css instead of id. Something along these lines:
var btns = document.getElementsByClassName("btn");
for(var i = 0; i < btns.length; i++){
btns[i].addEventListener("click", function(e) {
var clss = e.target.getAttribute("class")
if(clss === undefined || cls === null){clss = "";}
if(cls.indexOf("blue-spinner") > -1){
var output = "You clicked a blue spinner";
e.target.setAttribute("class", "orange-spinner");
}else{
e.target.setAttribute("class", "blue-spinner");
var output = "You clicked an orange spinner";
}
var h = document.getElementById("h1");
h.innerHTML = output;
});
}
Since you change the id for the element you have to update your code after the change.
document.addEventListener("DOMContentLoaded", function() {
var blueSpin = document.getElementById("blue-spinner");
var orangeSpin = document.getElementById("orange-spinner");
var blueSpinClick = function() {
document.getElementById("h1").innerHTML = "You've Clicked Blue";
blueSpin.removeEventListener('click', blueSpinClick);
orangeSpin.removeEventListener('click', orangeSpinClick);
blueSpin.removeEventListener('click', blueSpinClick);
blueSpin.setAttribute("id","orange-spinner");
orangeSpin.setAttribute("id", "blue-spinner");
blueSpin = document.getElementById("blue-spinner");
orangeSpin = document.getElementById("orange-spinner");
blueSpin.addEventListener("click", blueSpinClick);
orangeSpin.addEventListener("click", orangeSpinClick);
}
document.getElementById("blue-spinner").addEventListener("click", blueSpinClick);
var orangeSpinClick = function() {
document.getElementById("h1").innerHTML = "You've Clicked Orange";
orangeSpin.removeEventListener('click', orangeSpinClick);
blueSpin.removeEventListener('click', blueSpinClick);
blueSpin.setAttribute("id","orange-spinner");
orangeSpin.setAttribute("id", "blue-spinner");
blueSpin = document.getElementById("blue-spinner");
orangeSpin = document.getElementById("orange-spinner");
blueSpin.addEventListener("click", blueSpinClick);
orangeSpin.addEventListener("click", orangeSpinClick);
}
document.getElementById("orange-spinner").addEventListener("click", orangeSpinClick);
});
h1, h2 {
font-weight: bold;
text-align: center;
font-size: 45px;
font-family: 'VT323', monospace;
margin: 15px;
}
#blue-spinner {
color: blue;
}
#orange-spinner {
color: goldenrod;
}
<script src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"></script>
<html>
<body>
<h1 id="h1">Click Something:</h1>
<h2 id="blue-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
<h2 id="orange-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
</body>
</html>
I am trying to highlight the single line of text in <textarea> with time delay. And I am wondering if I can choose a different color? The thing I wanted is when I click on the first <button>, the first line is highlighted into blue, click on the second <button>, 1 second later, the second line is highlighted into blue, lastly click on the third <button>, 2 second later, the third line is highlighted into yellow. I noticed I have a bug that I clicked on the button 3 times then the highlight doesn't work, but it is okay for me, I just want to know how to make the time delay and highlight with a different color. Thank you very much.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function() {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>
You can use setTimeout() to set the delay in highlighting the text based on button id.
And ::selection css selector to style the portion of an element that is selected.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function(e) {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
var time = 0;
var tar_id = e.target.id;
var colors;
if(tar_id == 'line1' ) { colors = 'red'; }
else if(tar_id == 'line2' ) { time = 1000; colors = 'blue'; }
else if(tar_id == 'line3' ) { time = 2000; colors = 'green'; }
setTimeout(function(){
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
$('body').addClass(colors);
}, time);
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
.red ::selection {
color: red;
background: yellow;
}
.blue ::selection {
color: blue;
background: red;
}
.green ::selection {
color: green;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>
So I have a code so when I press a button a number goes up.
This is the html:
<button type="button" class="btn btn-default" onclick="javascript:btnClick()">+1</button>
This is the JavaScript:
function btnClick(){
timesClicked += 1;
document.getElementById('timesClicked').innerHTML = timesClicked;
return true
}
So I have a button that has +1 so when I press it the number goes up
I need a button that is disabled until that number gets to 5 for example then becomes clickable, is that possible? I'm still learning Javascript,
All help is appreciated.
If the button is disabled, a user cannot interact with it.
Try the following
window.onload=function() {
var count =0;
document.getElementById("btn").addEventListener("click", function() {
count++;
if(count === 5) {
this.innerHTML = "5 clicks reached!";
}
});
};
<button id="btn">Click</button>
You could try something like this:
document.getElementById("button").disabled = true;
timesClicked = 0;
function btnClick(){
timesClicked += 1;
document.getElementById('timesClicked').innerHTML = timesClicked;
if(timesClicked > 5){
document.getElementById("button").disabled = false;
}
}
<button type="button" id="button" class="btn btn-default" onclick="btnClick()">+1</button>
[].forEach.call(document.querySelectorAll("[data-click-vote]"), function(btn) {
btn.addEventListener("click", vote);
});
function vote() {
this.innerHTML = this.value=Math.min(++this.value, 5);
}
<button value="0" name="movie1" data-click-vote>+1</button> The Revenant<br>
<button value="0" name="movie2" data-click-vote>+1</button> Dracula<br>
<button value="0" name="movie3" data-click-vote>+1</button> The Usual Suspect<br>
Multiple buttons
Updates simultaneously value and innerHTML
You can submit the values using a <form>
You can achieve your requirement with JS and CSS as in the below solution.
You haven't tagged it with CSS but you might want to look at this as well.
Button is simply a disabled span. Clicks are registered and when the count requirement is satisfied, it springs to life and handles your clicks with the actual handler code. (You can add a handler instead of printing a click count)
window.onload = function() {
var count = 1;
document.getElementById("btn").addEventListener("click", function() {
count++;
this.innerHTML = "+" + count;
if (count >= 5) {
this.className = "btnenabled";
this.innerHTML = "Print Click Count!";
if(count > 5) {
document.getElementById("counter").innerHTML= "Click Count is " + count;
}
}
});
};
.btnenabled {
width:200px;
background-color: blue;
padding: 3px;
border-radius: 3px;
color: white;
font-weight: bold;
display:block;
text-align:center;
}
.btnenabled:hover {
background-color:purple;
}
.btndisabled {
width:200px;
padding: 3px;
border-radius: 3px;
display:block;
text-align:center;
background-color: grey;
color: #F0F0F0;
font-weight: 100;
}
<span id="btn" class="btndisabled"> +1 </span>
<span id="counter"></span>