Implementing buttons using css and jQuery - javascript

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>

Related

How to select elements where id is not

I have multiple divs, and I would like to give a style at one when I click on it. And delete the style of all others divs it when I click on one other div.
To add style, this works :
document.getElementById(i).classList.add('border-blue-400', 'border-b-2', 'border-l-4');
The answer has been removed, I dont know why but I did this :
let docs = document.querySelectorAll(':not([id^='+i+'])')
for(let doc of docs)
{
doc.classList.remove('border-blue-400');
}
and it works
thanks
To remove it, I tried this but it does not work :
document.querySelectorAll(':not([id^='+i+'])').classList.remove('border-blue-400');
You can add an event listener to each element using for example a class, when an element in the class is clicked, the function will go over every element in the class and remove the style you defined.
By passing the clicked element to the function, we can then use target.id to check if the element we are going over has the same ID as the element we clicked on, in which case we apply a different style.
document.querySelectorAll(".div").forEach(div => addEventListener("click", (element) => {
document.querySelectorAll('.div').forEach(div => {
if(div.id != element.target.id) {
div.style.border = "10px solid green";
}
else {
div.style.border = "10px solid black";
}
});
}));
.div {
height: 100px;
width: 100px;
border: 10px solid green;
background-color: green;
}
<!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">
<title>Document</title>
</head>
<body>
<div class="div" id="1"></div>
<div class="div" id="2"></div>
<div class="div" id="3"></div>
</body>
</html>

Using Buttons To Show Particular Divs and hide the rest

OK, I'm still mind boggled. I've done a ton here, and still can't see why the things aren't loading. I thought maybe it had to do with CORS, so I added a cookies rule to the script, but even then I find this weird, because I was able to display the podcast player locally just fine when I wasn't trying to hide and activate one or the other.
The code seems to be just fine however, I can't seem to pick out the problem.
document.cookie = "cookiename=cookievalue; SameSite=None; Secure; path="
// Add active class to default player and button
document.getElementById("player1-button").classList.add("active");
document.getElementById("player1").classList.add("active");
// Add event listeners to the buttons to listen for clicks and execute a function
document.getElementById("player1-button").addEventListener("click", function() {
//Remove active class from the current player and button
document.getElementById("player2-button").classList.remove("active");
document.getElementById("player2").classList.remove("active");
// Add active class to player1 and player1-button
document.getElementById("player1").classList.add("active");
this.classList.add("active");
});
document.getElementById("player2-button").addEventListener("click", function() {
//Remove active class from the current player and button
document.getElementById("player1-button").classList.remove("active");
document.getElementById("player1").classList.remove("active");
// Add active class to player2 and player2-button
document.getElementById("player2").classList.add("active");
this.classList.add("active");
});
This is my new javascript.
Furthermore, here's the related CSS:
.podcast-player div:not(.active) {
display: none;
}
.podcast-player div.active {
display: block;
}
and as well, the HTML for the player element:
<div class="podcast-player">
<!-- add the 2 embedded players here -->
<div id="player1">
<div id='buzzsprout-small-player'></div>
<script type='text/javascript' charset='utf-8' src='https://www.buzzsprout.com/2107108.js?container_id=buzzsprout-small-player&player=small'></script>
</div>
<div id="player2">
<div id='buzzsprout-large-player'></div>
<script type='text/javascript' charset='utf-8' src='https://www.buzzsprout.com/2107108.js?container_id=buzzsprout-large-player&player=large'></script>
</div>
</div>
I've been combing through this for the past few hours, and to me it all seems like it should work. I'm baffled.
Can you check the following code, and let me know if this is what you were looking for?
<!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">
<title>Document</title>
<style>
.player {
display: none;
}
.player.active {
display: block;
}
</style>
</head>
<body>
<div class="player active" id='buzzsprout-small-player'></div>
<div class="player" id='buzzsprout-large-player'></div>
<button disabled id="small-player-button">Activate Player Small</button>
<button id="large-player-button">Activate Player Large</button>
<script type='text/javascript' charset='utf-8'
src='https://www.buzzsprout.com/2107108.js?container_id=buzzsprout-large-player&player=large'></script>
<script type='text/javascript' charset='utf-8'
src='https://www.buzzsprout.com/2107108.js?container_id=buzzsprout-small-player&player=small'></script>
<script>
// Add event listeners to the buttons to listen for clicks and execute a function
document.getElementById("small-player-button").addEventListener("click", function () {
//Remove active class from the large player
document.getElementById("buzzsprout-large-player").classList.remove("active");
// Add active class to small player
document.getElementById("buzzsprout-small-player").classList.add("active");
// Enable large player button
document.getElementById("large-player-button").disabled = false;
// Disable small player button
this.disabled = true;
});
document.getElementById("large-player-button").addEventListener("click", function () {
//Remove active class from the small player
document.getElementById("buzzsprout-small-player").classList.remove("active");
// Add active class to large player
document.getElementById("buzzsprout-large-player").classList.add("active");
// Enable small player button
document.getElementById("small-player-button").disabled = false;
// Disable large player button
this.disabled = true;
});
</script>
</body>
</html>

Why is my button taking two clicks to toggle a function? 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>

Changing the background color with click using queryselector (JS)

I have written this code for these buttons, so when I click on them, the background color changes, but it doesn't work. what seems to be the problem?
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<title>JavaScript Background Color Switcher</title>
</head>
<body>
<div class="canvas">
<h1>Color Scheme Switcher</h1>
<span class="button" id="grey"></span>
<span class="button" id="white"></span>
<span class="button" id="blue"></span>
<span class="button" id="yellow"></span>
</div>
<script src="app.js"></script>
</body>
</html>
JS File:
document.querySelector('.button').addEventListener('click', function btn (id) {
document.body.style.background = id
})
There are two problems with your code:
1) document.querySelector will only return the first matching element
2) the click event does not take a function with such arguments.
Better code would be:
document.querySelectorAll('.button')
.forEach(btn =>
btn.addEventListener('click', () => document.body.style.background = btn.id)
);
(here I reuse btn again instead of using the data from the event because I already know which button you hit, so no need to mess around with ev.target...
You must use .querySelectorAll to add a listener on all the .button elements.
I also corrected the syntax for your addEventListener
let btns = document.querySelectorAll('.button')
btns.forEach(btn => {
btn.addEventListener('click', evt => {
document.body.style.background = evt.target.id
})
})
.button { cursor: pointer; }
<div class="canvas">
<h1>Color Scheme Switcher</h1>
<span class="button" id="grey">Grey</span>
<span class="button" id="white">White</span>
<span class="button" id="blue">Blue</span>
<span class="button" id="yellow">Yellow</span>
</div>
use document.querySelectorAll instead document.querySelector
let buttons = document.querySelectorAll('.button')
buttons.forEach(element=>{
element.addEventListener('click', (e) => {
document.body.style.background = e.target.id
})
})
span{
padding: 4px 6px;
border: 1px solid;
cursor: pointer;
}
#grey{
background :grey;
}
#white{
background :white;
}
#blue{
background :blue;
}
#yellow{
background :yellow;
}
<div class="canvas">
<h1>Color Scheme Switcher</h1>
<span class="button" id="grey">gray</span>
<span class="button" id="white">white</span>
<span class="button" id="blue">blue</span>
<span class="button" id="yellow">yellow</span>
</div>
You can

Display a div using a javascript function

I'd like to display a div on a webpage when a user clicks on a button.
Does someone know how to do this ?
My code, so far, is :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
</head>
<body>
<input id="text" type="text" size="60" value="Type your text here" />
<input type="button" value="When typing whatever text display the div balise on the page" onclick="check();" />
<script type="text/javascript">
function check() {
//Display my div balise named level0;
}
</script>
</body>
</html>
Thanks,
Bruno
EDIT: All my code (I've erased it because it was too long and not very clear)
You can use document.createElement("div") to actually make the div. Then you can populate the div using innerHTML for the text. After that, add it to the body using appendChild. All told, it can look like this:
function check() {
var div = document.createElement("div");
div.innerHTML = document.getElementById("text").value;
document.body.appendChild(div);
}
This will add a div every time the button is pressed. If you want to update the div each time instead, you can declare the div variable outside the function:
var div;
function check() {
if (!div) {
div = document.createElement("div");
document.body.appendChild(div);
}
div.innerHTML = document.getElementById("text").value;
}
If you have the div already in the page with an id of "level0", try:
function check() {
var div = document.getElementById("level0");
div.innerHTML = document.getElementById("text").value;
}
A quick search on google gave me this example:
Demo of hide/show div
The source-code for that example is:
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<html>
<head>
<title>Demo of Show hide div layer onclick of buttons</title>
<META NAME="DESCRIPTION" CONTENT="Displaying and hiding div layers through button clicks">
<META NAME="KEYWORDS" CONTENT="Show layer, hide layer, display div, hide div, button on click, button on click event, div property, div style set">
<style type="text/css">
div {
position: absolute;
left: 250px;
top: 200px;
background-color: #f1f1f1;
width: 280px;
padding: 10px;
color: black;
border: #0000cc 2px dashed;
display: none;
}
</style>
<script language="JavaScript">
function setVisibility(id, visibility) {
document.getElementById(id).style.display = visibility;
}
</script>
</head>
<body>
<input type=button name=type value='Show Layer' onclick="setVisibility('sub3', 'inline');";><input type=button name=type value='Hide Layer' onclick="setVisibility('sub3', 'none');";>
<div id="sub3">Message Box</div>
<br><br>
</body>
</html>
Paste this code somewhere in your body
<div id="myDiv" style="display:none">
Hello, I am a div
</div>
Add this snippet into your check() function to display the otherwise-hidden content.
document.getElementById("myDiv").style.display = "block";
You could also change the div content programmatically thus:
document.getElementById("myDiv").innerHTML = "Breakfast time";
... would change the text to 'Breakfast time'.
You might want to look into jquery, it'll make your life 100 times easier.
Jquery is a javascript library (script) that you include and it allows you to manipulate the DOM very easily.
Start by adding the latest Jquery to your head which will allow you to use something like $(document).ready( )
The function inside .ready( fn ) is a callback function; it get called when the document is ready.
$("#lnkClick") is a selector (http://api.jquery.com/category/selectors/)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready( function() {
$("#lnkClick").click( function() {
$("#level0").attr("style", "display: block;width: 100px; height: 100px; border: solid 1px blue;");
});
});
</script>
</head>
<body>
<div id="level0" style="display:none;">
</div>
Click me
</body>
</html>
Of course this code can be made cleaner. You want to check: http://api.jquery.com/click/
There are plenty of examples.
Best of luck with Jquery!
you really should be using jquery , there's a little bit of a learning curve but once you get it, developing web apps is much easier.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script>
$(document).ready(function() {
$("#show_div_button").click(function() {
$("#div_to_show").show();
return false;
});
});
</script>
</head>
<body>
Click Me to Show the Div
<div style="display:none" id="div_to_show">I will be shown when the link is clicked</div>
</body>
</html>

Categories