Why is my button taking two clicks to toggle a function? JavaScript - javascript

I have created a webpage with a button. When you click it, it turns from the default black to pink and when you click it again, it turns purple. For some reason, it is taking two clicks to turn from the default black button to pink. Please help me figure out how to make it so it changes on the first click (or if you know a better way to carry this out)
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Events Lab</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="changeh1"> Clicking the button will change its color <h1>
<button onclick="changeStyle()" type="button" name="button" id="buttonStyle">My color will change!</button>
<script src="script.js"></script>
</body>
</html>
JavaScript
function changeStyle() {
//sets variable "button" to connect to HTML ID "buttonStyle"
var button = document.getElementById("buttonStyle"),
click = false;
button.onclick = function() {
click = !click;
//toggles background color back and forth between pink and purple when you click button
button.style.background = click? "#ff0066": "#9933ff";
//toggles text back and forth between "I am now pink!" and "I am now purple!"
document.getElementById('buttonStyle').innerHTML = click? 'I am now pink!': 'I am now purple!';
}
}
let buttonClick = document.getElementById('buttonStyle');
buttonClick.addEventListener('click', changeStyle);
CSS
body{
text-align: center;
font-family: Helvetica;
}
button {
width:350px;
height: 125px;
background-color: black;
color:white;
border: 5px solid black;
font-size: 20px;
}

In your javascript, you wrote the below codelines.
let buttonClick = document.getElementById('buttonStyle');
buttonClick.addEventListener('click', changeStyle);
Also in your html you wrote the code like the below.
<button onclick="changeStyle()" type="button" name="button" id="buttonStyle">My color will change!</button>
Meaning, when you click the My color will change! button, the changeStyle function will be called twice.
Why?
One from the event defined in html code and the other one from the event defined in javascript code.
In case you remove the above 2 codelines in javascript it will work correctly.
Or else, you can remove the onclick event in the html code like this :
<button type="button" name="button" id="buttonStyle">My color will change!</button>

You added eventListener two times, one in HTML onclick, the other one in Javascript with addEventListener.
You can make Javascript code as simple as follows:
var click = false;
let buttonClick = document.getElementById('buttonStyle');
function changeStyle() {
click = !click;
//toggles background color back and forth between pink and purple when you click button
buttonClick.style.background = click? "#ff0066": "#9933ff";
//toggles text back and forth between "I am now pink!" and "I am now purple!"
buttonClick.innerHTML = click? 'I am now pink!': 'I am now purple!';
}
body{
text-align: center;
font-family: Helvetica;
}
button {
width:350px;
height: 125px;
background-color: black;
color:white;
border: 5px solid black;
font-size: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Events Lab</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="changeh1"> Clicking the button will change its color <h1>
<button onclick="changeStyle()" type="button" name="button" id="buttonStyle">My color will change!</button>
<script src="script.js"></script>
</body>
</html>

Related

Implementing buttons using css and jQuery

I'm a complete beginner.
I'm trying to implement two buttons that change colors (green to blue) with one click (and once the implementation is completed, integrating it to the actual website).
The buttons need to do the following:
Both the buttons are initially green. Once a button is clicked, it should change its color to blue.
And after that same button is clicked the second time, it should revert back to its original color which is green.
Only one button out of the two can be blue at a time. Which means as soon as the user clicks button-2 after clicking button-1, the button-1 should turn back to green, and button-2 to blue.
So far, I can implement the first and third ones, but not the middle one.
Here are the necessary codes for it:
$(document).ready(function () {
$('#btn1').click(function(){
$('.btn').css('background-color', 'green');
$(this).css('background-color', 'blue');
})
$('#btn2').click(function(){
$('.btn').css('background-color', 'green');
$(this).css('background-color', 'blue');
})
});
.btn {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/styles.css">
<title>Document</title>
</head>
<body>
<button id = "btn1" class = "btn">Button</button>
<button id = "btn2" class = "btn">Button</button>
<!--<button id = "btn3" class = "btn" onclick="changeColor()">Button</button>
<button id = "btn4" class = "btn" onclick="changeColor()">Button</button> -->
<script src="/jquery-3.6.1.min.js"></script>
<script src="/index.js"></script>
</body>
</html>
To do what you require you can toggle a class on the clicked element which sets its background to blue. At the same time this class will be removed from all other buttons.
The code can also be simplified by using a single event handler bound to all .btn elements, instead of separate ones for each id.
jQuery($ => {
let $btns = $('.btn').on('click', e => {
let $btn = $(e.target).toggleClass('clicked');
$btns.not($btn).removeClass('clicked');
});
});
.btn {
background-color: green;
}
.btn.clicked {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>
Rory's answer is probably the best, but I think this one is more easy to understand for a beginner (although less elegant):
$('.btn').click(function(){
if ($(this).hasClass('clicked')) {$(this).removeClass('clicked');}
else {$('.btn').removeClass('clicked'); $(this).addClass('clicked');}
});
.btn {
background-color: green;
}
.clicked {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Button</button>
<button class="btn">Button</button>

How do i change the text on a button on mouse hover?

I need to make a button that changes the text inside it when the cursor is over it, and changes it back when the cursor leaves the box.
I have tried on VScode with "document.getElementById().innerHTML" but it just changes the text when the cursor goes on and it doesnt go back to the original text.
button {
background-color: green;
border-color: white;
border-radius: 10px;
align-self: center;
}
body {
background-color: black;
}
h1 {
color:green;
text-align: center;
}
p {
color: chartreuse;
font-family: Verdana;
font-size: 12px;
}
button:hover{
background: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="website.css">
</head>
<body>
<h1>Web Page</h1>
<!-- Buttons -->
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click to display Date and Time</button>
<p id="demo"></p>
<button type="button"
onmouseover="this.innerHTML = Date()"
onmouseout="document.getElementById">What time is it</button>
<script>
var x = "What time is it";
document.getElementById("time").innerHTML = x;
</script>
You can use mouseenter and mouseleave event and then can change innerHTML of the button.
const btnEle = document.getElementById("btn");
btnEle.addEventListener('mouseenter', e => {
btnEle.innerHTML = "Save";
});
btnEle.addEventListener('mouseleave', e => {
btnEle.innerHTML = "Submit";
});
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="btn">Submit</button>
</div>
</body>
</html>
How I would do it is to have two <span>'s in my button. The first <span> will contain the text you want to show by default. The second <span> will contain the text you want to show on hover. This span is hidden by default.
Then, you could add an event listener to your button. On mouseover, hide the default text and show the span containing the hover text. In a mouseleave event listener, just do the opposite.
HTML:
<button id="myid">
<span class="default-text">Text 1</span>
<span class="hover-text" style="display: none;">Text 2</span>
</button>
JS:
var button = document.getElementById('myid')
button.addEventListener('mouseover', function() {
this.querySelector('.hover-text').style.display="block";
this.querySelector('.default-text').style.display="none";
});
button.addEventListener('mouseleave', function() {
this.querySelector('.default-text').style.display="block";
this.querySelector('.hover-text').style.display="none";
});

Can you hide a div based on a buttons state being "false" when clicked with JS?

Basically I have a button, and when the button has been minimised and the person has finished the chat and the changes the attribute state of the button changes to <button aria-expanded="false"> , I need the whole chat div <div id="beacon-container"> to become hidden on the page.
Is this possible to target this specific attribute if I'm unable to edit the chat button and div code itself as it's an off-page call in?
Many thanks
Am not sure how you have implemented this already so I have just provided you with a solution that is quite open
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
Credit: https://www.w3schools.com/howto/howto_js_toggle_hide_show.asp

set the visibility of buttons

I am creating a web app in which i want to use a date picker
<script src="js/bootstrap-datetimepicker.min.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="documents/css/reset.css"/>
<link rel="stylesheet" href="css/BeatPicker.min.css"/>
<link rel="stylesheet" href="documents/css/demos.css"/>
<link rel="stylesheet" href="documents/css/prism.css"/>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/BeatPicker.min.js"></script>
these are the script and link i downloaded from the web
this is my input field where i want to use datepicker
<body>
<input type="text" data-beatpicker="true"/>
</body>
but there is a by default button with the textbox
i used the css to remove the button by making the visibility:hidden;
<style>
button, input[type="button"] {
background-color: #D36161;
border: medium none;
color: #FFFFFF;
cursor: pointer;
font: bold 14px arial,serif;
margin: 3px;
padding: 4px;
visibility: hidden;
width: 72px;
}
</style>
but when i try to add another button it also disabled because of the stylesheet where i put visibility:hidden
this is my button with id
<button id="butt">close</button>
i edited th stylesheet like this
<style>
.butt{
visibility:visible;
}
</style>
but still it is not showing me the desired button
how can i do? i want to disable the button with textbox but visible other button
You are using a library called "BeatPicker".
Before messing arrond with the css, you should read the documentation.
To remove the 'clear' button you will need to add the following attribute to the date input
data-beatpicker-module="clear"
This will remove the clear button
More features are available here: http://act1gmr.github.io/BeatPicker/demos.html
A class selector is preceded by ., and an ID selector is preceded by #. So in your code, change the selector to #butt, because it is the ID of your button.
Try something like this:
<!DOCTYPE html>
<html>
<head>
<style>
button.visible {
visibility: visible
}
button.hidden {
visibility: hidden
}
</style>
</head>
<body>
<button class="visible">This is a visible button</button>
<button class="hidden">This is an invisible button</button>
<button>Notice that the invisible button still takes up space.</button >
</body>
</html>
Do the following
change button, input[type="button"] to .beatpicker-clearButton so you don't have this problem any more or as Adi Darachi sad add clear to the data-beatpicker-module attribute to remove the button
Use this
<body>
<input type="text" data-beatpicker="true" data-beatpicker-position="['*','*']" data-beatpicker-module="today,clear" />
</body>
Add the following css. This will hide only the beatpicker clear buttons.
.beatpicker-clearButton {
display: none;
}

Duplicating div elements and their CSS on button click

I'm working on a page that has a div with the id "exam" and a button with the id "copy". The div includes the text "Exam 1" and has a 2px double black border around it. When the button is clicked, the div element is supposed to be duplicated and displayed below each time the button is clicked. I have gotten that part to work, however, it doesn't seem to be copying the div element's CSS, only the text inside the element, so each time I click the button, it's only displaying "Exam 1", but not the border.
Here is my HTML (this also includes the Javascript and CSS):
<html>
<head>
<title>Exam 1 Tanner Taylor</title>
<style type="text/css">
#exam {
border: 2px double black;
}
</style>
</head>
<body>
<div id="exam">
Exam 1
</div>
<input type="button" id="copy" value="Make Copy" onclick="copy()" >
</body>
<script type = "text/javascript">
var TTi = 0;
var TToriginal = document.getElementById("exam");
function copy() {
var TTclone = TToriginal.cloneNode(true);
TTclone.id = "exam" + ++TTi;
TToriginal.parentNode.appendChild(TTclone);
}
</script>
</html>
There's more to it, but I cut out the portions that didn't deal with this particular issue. Any ideas as to why it's not displaying the border around the text when the button is clicked?
The css is only targeting the id exam and all clones are changing that id. A possible solution would be to use [id^="exam"].
^= says if it starts with "exam" then use this style.
DEMO: http://jsbin.com/xupuqavecope/2/edit
<html>
<head>
<title>Exam 1 Tanner Taylor</title>
<style type="text/css">
[id^="exam"] {
border: 2px double black;
}
</style>
</head>
<body>
<div id="exam">
Exam 1
</div>
<input type="button" id="copy" value="Make Copy" onclick="copy()" >
</body>
<script type = "text/javascript">
var TTi = 0;
var TToriginal = document.getElementById("exam");
function copy() {
var TTclone = TToriginal.cloneNode(true);
TTclone.id = "exam" + ++TTi;
TToriginal.parentNode.appendChild(TTclone);
}
</script>
</html>

Categories