Javascript Show/Hide certain elements by clicking a button - javascript

I have 12 tiles (100px by 100px squares) on my screen.
Each tile by default is set to display:block and has a white background background: rgb(255,255,255);
If a tile is clicked, the background becomes orange rgb(255,161,53). Using the following function:
function changeColour(id){
{
var current_bg = document.getElementById(id).style.backgroundColor;
if(current_bg != "rgb(255, 161, 53)"){
document.getElementById(id).style.backgroundColor = "rgb(255,161,53)";
} else if(current_bg == "rgb(255, 161, 53)"){
document.getElementById(id).style.backgroundColor = "rgb(255,255,255)";
}
}
At the bottom of the page I have a button called "showHide", once it is pressed I want only the tiles with an orange background to be shown. Once it pressed again I want ALL of the tiles to appear.

What I meant with meta data
A break down:
The first block iterates over every tile and sets an onclick handler
When you click a block it will either set orange to the class list or remove it using toggle. The actual orange coloring comes from the stylesheet. Where tiles that don't have orange in their class names :not() get a white background.
When you click the show hide button you'll see the same trick. Every class list that doesn't contain orange get hidden by the hide class name that gets toggled.
I've used a different approach here, using class names as selectors and play with them to get the desired result.
function changeColour() {
this.classList.toggle("orange");
//if hiding is on we need to also hide that block
if (this.parentElement.querySelectorAll("div.tiles.hide").length > 0)
{
this.classList.add("hide");
}
}
var divs = document.querySelectorAll("div.tiles");
//use Array.prototype.forEach to iterate over nodelist
Array.prototype.forEach.call(divs, function(element){
element.addEventListener("click", changeColour);
});
document.querySelector("button.hide").addEventListener("click", showHide);
function showHide(){
Array.prototype.forEach.call(divs, function(element){
if (!element.classList.contains("orange"))
{
element.classList.toggle("hide");
}
});
}
div.tiles {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid grey;
}
div.tiles:not(.orange) {
background-color: #ffffff;
}
div.tiles.orange {
background-color: rgb(255,161,53);
}
div.tiles.hide {
display: none;
}
<div class="tiles"></div>
<div class="tiles"></div>
<div class="tiles"></div>
<div class="tiles"></div>
<div class="tiles"></div>
<button class="hide">show/hide white tiles</button>

Related

Add class if image has the class

I have some images which are way too big when I make the menu they're containing in smaller, that's why I made a second class where I changed the width and height.
I tried to add and remove the class with javascript like this:
if ($('img').hasClass('lorem')) {
$('img').removeClass('lorem')
$('img').addClass('smalllorem')
} else {
$('img').addClass('lorem')
$('img').removeClass('smalllorem')
}
Now this works perfectly fine, but this will add the classes to my other images on the website as well, how can I specify to only give the class "smalllorem" to the elements which have the class lorem? Because the other images don't have the class "lorem" they will still get the class "smalllorem" added on.
-> I don't get why images without the class "lorem" get into the code? I mean I ask if the image has class .. Why does it include the other image elements?
I would look for a CSS solution before moving on to a JavaScript one. But answering the question asked...
I don't get why images without the class "lorem" getting into the code ? I mean I ask if img has class
Because $("img") selects all images, but $("img").hasClass("lorem") only looks at the first image to see if it has the class. Then in each branch of your if/else, you're applying changes to all images ($("img").addClass("lorem");). jQuery's API is asymmetric in this regard: methods that tell you something about the element only look at the first element in the jQuery collection, but methods that change something apply to all elements in the collection.
If I understand you correctly, you want to:
Remove lorem from images that have it, adding smalllorem instead
and
Remove smalllorem from images that have it, adding lorem instead
Basically, you want to toggle both classes. There's a toggleClass method for that.
$("img.lorem, img.smalllorem").toggleClass("lorem smalllorem");
That selects all img elements that have either class, and toggles the classes on them.
Live Example:
setTimeout(() => {
$("img.lorem, img.smalllorem").toggleClass("lorem smalllorem");
}, 800);
.lorem {
border: 2px solid black;
}
.smalllorem {
border: 2px solid yellow;
}
<div>lorem (black border) => smalllorem (yellow border):</div>
<img class="lorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="lorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="lorem" src="https://via.placeholder.com/50.png/09f/fff">
<div>smalllorem (yellow border) => lorem (black border):</div>
<img class="smalllorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="smalllorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="smalllorem" src="https://via.placeholder.com/50.png/09f/fff">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Instead of adding a new class to the image you could just make it responsive :
.img {
width: 100%; //define width
max-width: 250px; //restrict the size (can use min-width aswell)
height: auto; //auto adjust depending on the width
}
var count = 0;
function resize(){
var menue = document.getElementById("container");
count++;
if(count % 2)
{
menue.style.width = "50%";
menue.style.height = "50px";
}
else
{
menue.style.width = "100%";
menue.style.height = "100px";
}
}
#container{
border: 1px solid black;
width: 100%;
height: 100px;
transition: 330ms;
}
#home{
width: 15%;
height: auto;
min-width:10px;
}
menue
<div id="container">
<img src="https://cdn-icons-png.flaticon.com/512/25/25694.png" id="home">
</div>
<br>
<input type="button" value="resize menue" onclick="resize()">

Change one button background color onClick and revert previously clicked button to default background (8 Buttons)

I have a column of 8 buttons and would like only one button to be toggled(yellow) at a time and the rest of the buttons remain default(green).
I am having a bear of a time getting the function to execute on click. Meaning no colors are changing.
I have been using this post How to select and change color of a button and revert to original when other button is clicked
as my reference and has helped me understand querySelectors and changing classes but for the life of me I cant see why my application isnt working.
Console.log('test) fires right after the for loop is called but if put below the onClick it does not fire.
JS
for (button in buttons) {
buttons[button].onclick = function() {
console.log('test')
var yellowButton = document.querySelectorAll(".yellow")[0];
if (this.className == "green") {
if (yellowButton) yellowButton.className = "green";
this.className = "yellow";
}
}
}
HTML
<button class="green">UPKEEP</button>
<button class="green">DRAW</button>
<button class="green">MAIN</button>
<button class="green">COMBAT</button>
<button class="green">MAIN</button>
<button class="green">END TURN</button>
<button class="green">CLEANUP</button>
CSS
button{
width: 100%;
padding: 10px 20px;
margin: 3px;
}
.green{
background-color: green;
}
.yellow {
background-color: yellow;
}
I am expecting to have 1/8 of the buttons to be yellow. That being the clicked button.
Rather than toggling the yellow and green classes - you can simply add a 'highlight' class on click and remove it from the previously clicked button.
This highlight class has the yellow background styling, so that when you click a button it adds the highlight class and yellow background. Then clicking another button removes the highlight class from the first button and applies it to the clicked one.
var buttons = document.querySelectorAll("button");
for (button in buttons) {
buttons[button].onclick = function() {
console.log('test')
buttons.forEach(function(btn){
btn.classList.remove('highlight');
})
this.classList.add('highlight');
}
}
button{
width: 100%;
padding: 10px 20px;
margin: 3px;
}
.green{
background-color: green;
}
.highlight {
background-color: yellow;
}
<button class="green">UPKEEP</button>
<button class="green">DRAW</button>
<button class="green">MAIN</button>
<button class="green">COMBAT</button>
<button class="green">MAIN</button>
<button class="green">END TURN</button>
<button class="green">CLEANUP</button>
I managed to get your code to work. jsFiddle
Make sure you define buttons correctly:
var buttons = document.querySelectorAll(".green");
My problem was in my html, i had to move the script tag to the end of the body to allow loop to occur. Thanks for the help folks!

for a particular click remove the tick mark from check box and use red color inside checkbox

If I click third time the small check box should turn into red color and tick mark should not show inside the text box.instead of tick mark inside the check box it should show red color inside the check box.
can you tell me how to fix it.
providing my code below.
https://stackblitz.com/edit/angular-sq2q93?file=app%2Fapp.component.ts
public open(event) {
// attach event to button
this.count = this.count + 1;
console.log('this.count--->' + this.count);
if (this.count % 3 == 0) {
// apply new style
console.log('multiple of 3--->' + this.count);
this.multipleOf3 = true;
}
else {
this.multipleOf3 = false;
}
}
Checkboxes can not be styled. You would need a third party js plugin and there are many available. ( like this one http://icheck.fronteed.com/ )
But if you want to do this yourself it basically involves hiding the checkbox and creating an element and styling that as you want, then you display it or hide it whenever the checkbox is checked or not.
in your case, you can either create an element next to the checkbox, style it and hide it, then display it whenever you add the .multiple-of-3 class,
or simply hide the checkbox in multiple-of-3 class like so ( according to the example you provided in the link ) :
app.component.html
<label [ngClass]="{'is-multiple-of-3':multipleOf3}">
<span id="redSquare"></span>
<input type="checkbox" name="rememberLogin" id="buttonId" (click)="open()"> click me
</label>
app.component.css
/* if you want to create an element on top of the checkbox */
#redSquare{
width: 13px;
height: 13px;
background: red;
display: block;
margin-bottom: -16px;
z-index: 99;
position: relative;
left: 4px;
visibility: hidden;
}
.is-multiple-of-3 #redSquare{
visibility: visible;
}
/* if you want to simply hide it */
.is-multiple-of-3 checkbox{
display: none;
}

Mouseout and click

When a user mouses over a div it should change to the color red, when they mouse out it should change back to transparent. When they click on the div, it should change to color red.
For some reason, the mouse out event listener is conflicting with the click event listener. Can someone help? When I click on the div, it doesn't change to red.
div$.on('mouseover', function () {
$(this).css('background-color', 'red');
});
div$.on('mouseout', function () {
$(this).css('background-color', 'white');
});
div$.on('click', function () {
$(this).css('background-color', 'red');
});
Note, I have to apply a background image dynamically to each element, so using CSS classes to add the background image is out of the question (because I don't know it before hand).
You could set a boolean variable to confirm that the click has occurred and then only run the mouseout code if the variable is false like this:
var is_clicked = false;
div$.on('mouseover', function () {
$(this).css('background-color', 'red');
});
div$.on('mouseout', function () {
if(!is_clicked) {
$(this).css('background-color', 'white');
}
});
div$.on('click', function () {
$(this).css('background-color', 'red');
is_clicked = true;
});
Note: For multiple div elements user multiple is_clicked variables
You can always do a CSS implementation with :hover; just make sure to add a specifying class to each element you would like this effect on.
1. :hover and jQuery
var div$ = $('.redHover'); // name the class whatever you like
div$.on('click', function () {
$(this).css('background-color', 'red');
});
div {
display: inline-block;
}
.redHover {
height: 100px;
width: 100px;
border: 1px solid black;
}
.redHover:hover {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='redHover'></div>
<div class='redHover'></div>
<div class='redHover'></div>
2. :hover and vanilla JS
var els = document.querySelectorAll('.redHover');
for (var i = 0; i < els.length; ++i) {
els[i].addEventListener('click', function() {
this.style.backgroundColor = 'red';
});
}
div {
display: inline-block;
}
.redHover {
height: 100px;
width: 100px;
border: 1px solid black;
}
.redHover:hover {
background: red;
}
<div class='redHover'></div>
<div class='redHover'></div>
<div class='redHover'></div>
Instead use mouseenter insead of mouseover see why.
The best thing you can go with would be the following notes:
To those elements with hover effect add a class like hoverable.
Hover effect is only applied to those elements having this class.
HTML:
<div class="hoverable"></div>
CSS:
.hoverable:hover{
background-color: red
}
JavaScript:
div$.on('click', function () {
$(this).css('background-color', 'red');
});
In this way, you can simply decide whether an element should be hover-able or not by adding or removing hoverable class. Also hover effect is applied in CSS level not JavaScript, which is more acceptable.
As far as I understand you really want to change picture in the div, not just background color which is relatively easy. Try this:
<div class="hoverable">
<img src="myImg.jpg" />
</div>
//css
.hoverable img{visibility:hidden;}
.hoverable:hover img{visibility:visible;}
.clicked img{visibility:visible!important;}
//JS
$('.hoverable').click(function(){
$(this).addClass('clicked');
});

Change div background image, js works in chrome but not ie or firefox?

Basically I want the user to be able to click and change the background, and for there to be multiple backgrounds, for a specific div.
This works perfectly in Google Chrome but not in IE or Firefox.
HTML:
<div id="palette">
<div class="lightblue"></div>
<div class="gold"></div>
<div class="aqua"></div>
</div>
<div id="primary">
</div>
CSS:
#palette {
border: 2px solid white;
width: 25px;
}
#palette div {
height: 25px;
width: 25px;
}
.lightblue {
background: lightblue url(http://www.textureking.com/content/img/stock/big/DSC_4279.JPG);
}
.gold {
background: gold url(http://www.textureking.com/content/img/stock/big/DSC_4287.JPG);
}
.aqua {
background: aqua url(http://www.textureking.com/content/img/stock/big/DSC_4274.JPG);
}
JS:
$(document).ready(function() {
// attach onclick event to your palette colors
$('#palette div').on('click', function() {
// get background of selected palette color
var bg = $(this).css('background');
// change the background of the body
$('#primary').css({ 'background': bg });
});
});
http://jsfiddle.net/KNutQ/1/
It's not showing any errors and other javascripts run, so I'm not really sure what the problem is.
If it's easy to fix please leave an answer, if not I will try it this way: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_backgroundimage
According to the CSS specification getting the computed style of a shorthand should not return anything. You need to list out the individual properties as I've done below.
Perhaps the CSS spec or Chrome will change in the future but at the moment Firefox and IE's behaviour is correct.
$(document).ready(function() {
// attach onclick event to your palette colors
$('#palette div').on('click', function() {
// get background of selected palette color
var backgrounds = $(this).css(['background-color','background-image', 'background-repeat', 'background-attachment', 'background-position']);
// change the background of the body
$('body').css(backgrounds);
});
});

Categories