Changing the function of a button in a website - javascript

So below I have some code of what I'm working with. Right now, if you just launch the website, the #picture div has a background image, and if you press any of the buttons, that picture is replaced with something else.
So what I can't figure out is how the buttons would change what they do after pressing a button. Let's say you click on Button 1 and the background image is replaced. I want the buttons to recognize what background image is in that div and change functions accordingly, in my case, I want them to change what pictures they replace the current one with.
If the current background of #picture is X, you have ABC choices, if the background of #picture is Y, you have DEF choices, would be a TLDR explanation maybe.
<div id="adventure">
<div class="picture">
</div>
<div id="choice">
<button class="button1">Val 1</button>
<button class="button2">Val 2</button>
<button class="button3">Val 3</button>
</div>
</div>
$('.button1').click(function() {
$('.picture').css('background-image',
'url("image1")'
);
});
$('.button2').click(function() {
$('.picture').css('background-image',
'url("image2")'
);
});
$('.button3').click(function() {
$('.picture').css('background-image',
'url("image3")'
);
});
I've probably gone about doing this in a bad way but I'm really at a loss on how I would do this. I can only think up of one way of doing it and that is to have a bunch of if statements depending on what background is in the #picture div but I don't know how to implement that.

This demo relies on the class .active which determines which set of buttons (called .group) are visible, whilst the other .groups remain absent. The #switch button will toggle through each group.
You must name your images according to the id of the button it belongs to.
Example:
HTML of Button
<button id="image_of_sky.png">D</button>
URL to Image
http://domain.com/path/to/image_of_sky.png
jQuery img variable
var img = "http://domain.com/path/to/"+btn;
Snippet
$('.button').click(function() {
var btn = $(this).attr('id');
var img = "https://placehold.it/330x150?text=" + btn;
$('.picture').css('background-image',
'url(' + img + ')'
);
});
$('#switch').click(function() {
var act = $('.group.active');
var next = act.next();
act.removeClass('active');
next.addClass('active');
if (act.attr('id') == "choiceGHI") {
$('#choiceABC').addClass('active');
}
});
#adventure {
width: 395px;
}
.picture {
width: 330px;
height: 150px;
border: 1px outset grey;
}
.group {
width: 330px;
display: none;
padding: 0;
}
.button {
width: 32.5%;
margin: 0;
}
.active {
display: block;
}
#switch {
float: right;
margin: -20px 0 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="adventure">
<div class="picture"></div>
<div id="choiceABC" class="group active">
<button id="Image1" class="button">A</button>
<button id="Image2" class="button">B</button>
<button id="Image3" class="button">C</button>
</div>
<div id="choiceDEF" class="group">
<button id="Image4" class="button">D</button>
<button id="Image5" class="button">E</button>
<button id="Image6" class="button">F</button>
</div>
<div id="choiceGHI" class="group">
<button id="Image7" class="button">G</button>
<button id="Image8" class="button">H</button>
<button id="Image9" class="button">I</button>
</div>
<button id="switch">Switch</button>
</div>

Related

Two Column Accordion with Separate Full Width Divs

The intension is to have a two column accordion, without limiting the "expand" field to the left or right column. The catch is that there will be multiple on one page. This is already created, but only button 1 is working. With the way my JS is going, it will get very very repetitive - I am looking for assistance with re-writing the JS to be multiple click friendly. Fiddle: https://codepen.io/ttattini/pen/abLzaaY
EDIT: It would also be perfect if one dropdown would close as the next is opened
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="row">
<div id="column">
<button id="button">I am Button #1</button>
<button id="button">I am Button #3</button>
</div>
<div id="column">
<button id="button">I am Button #2</button>
<button id="button">I am Button #4</button>
</div>
</div>
<div id="hidden">
<p id="content"> So here I am #1</p>
</div>
<div id="hidden">
<p id="content"> So here I am #2</p>
</div>
<div id="hidden">
<p id="content"> So here I am #3</p>
</div>
<div id="hidden">
<p id="content"> So here I am #4</p>
</div>
CSS
#hidden {
background: #ccc;
margin-top: 2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
#button {
padding: 10px;
margin-top: 5px;
width:50%;
margin-left: 10%;
cursor: pointer;
}
#row {
display: flex;
}
#column {
flex: 50%;
}
JS
$(function() {
var b = $("#button");
var w = $("#hidden");
var l = $("#content");
b.click(function() {
if (w.hasClass('open')) {
w.removeClass('open');
w.height(0);
} else {
w.addClass('open');
w.height(l.outerHeight(true));
}
});
});
The biggest issue is that you're using IDs when you should be using classes. IDs must be unique to each element in a page. When you repeat an ID, JS will only target the first element using that ID. That's why only the first one is working.
The second issue is that, because of the way the script is written, it will only target a single element. What you need to do is get all the elements you want to target by something like their class name and then loop through them, applying the event listener to each one and its appropriate children.
EDIT: Here is an example from some code I wrote for a page with multiple accordions a few weeks ago in vanilla JS
//Below I establish a counting variable and find all the accordions on the page
const acc = document.getElementsByClassName( 'accordion' );
let i;
//Looping through each accordion
for ( i = 1; i <= acc.length; i++ ) {
//Identify target for the event listener. In this case, a heading for each accordion, which I've numbered e.g. "title-1"
const title = 'title-' + i;
const label = document.getElementById( title );
//Identify target content, in this case a list that has a unique ID e.g. "list-1"
const listNum = 'list-' + i;
const list = document.getElementById( listNum );
//Add event listener to heading that toggles the active classes
label.addEventListener( 'click', function() {
label.classList.toggle( 'accordion--active' );
});
}
Of course, there's more than one way to skin a cat, but this is a working example.
I have tracked the clicked event of each button and showed the corresponding hidden content with the use of data- attribute.
I have used vanilla JavaScipt instead of jQuery.
const buttons = document.querySelectorAll('.button');
const hiddens = document.querySelectorAll('.hidden');
buttons.forEach((btn) => {
btn.addEventListener('click', btnClicked)
function btnClicked(e) {
hiddens.forEach((hidden) => {
if(e.target.dataset.btn == hidden.dataset.content) {
hidden.classList.toggle('height')
} else {
hidden.classList.remove('height')
}
})
}
})
.hidden {
background: #ccc;
margin-top: 2%;
padding-left:2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
.hidden.height {
height: 50px;
}
.button {
padding: 10px;
color: white;
background-color: #2da6b5;
border: none;
margin-top: 5px;
width:90%;
margin-left: 5%;
cursor: pointer;
}
.button:hover {
filter: brightness(.9);
}
#row {
display: flex;
}
.column {
flex: 50%;
}
<div id="row">
<div class="column">
<button class="button" data-btn="one">I am Button #1</button>
<button class="button" data-btn="three">I am Button #3</button>
</div>
<div class="column">
<button class="button" data-btn="two">I am Button #2</button>
<button class="button" data-btn="four">I am Button #4</button>
</div>
</div>
<div class="hidden" data-content="one">
<p class="content"> So here I am #1</p>
</div>
<div class="hidden" data-content="two">
<p class="content"> So here I am #2</p>
</div>
<div class="hidden" data-content="three">
<p class="content"> So here I am #3</p>
</div>
<div class="hidden" data-content="four">
<p class="content"> So here I am #4</p>
</div>
Also, please do not use the same ID at multiple elements.

how to distinguish between buttons with same className

Good day! I'm very new to Front-End development, and as a part of my homework I have got to use pure HTML, CSS and JavaScript only to make next thing:
6 button (likes) with same class name. I have different background images for one that wasn't clicked and one that was. In Demo I have background-color instead, does not matter I guess.
let pageCont = document.querySelector(`.page`);
let mainCont = pageCont.querySelector(`.container`);
let tableCont = mainCont.querySelector(`.table`);
let tableElem = tableCont.querySelector(`.table__element`);
let elemCont = tableElem.querySelector(`.table__text-container`);
var likeIcon = elemCont.querySelectorAll(`.table__like-icon`);
for (var i = 0; i < likeIcon.length; i++) {
likeIcon[i].addEventListener('onclick', function likeIconIsClicked()
{
likeIcon.classList.toggle(`table__like-icon_active`);
}
);
}
The idea was to change button(table__like-icon --> table__like-icon_acitve) properties. If I use var likeIcon = elemCont.querySelector(`.table__like-icon`) instead of querySelectorAll, I will be able to change only first found button which is not correct. So I used code that I had found on StackOverflow and tried to use it. Didn't work much. Here is the Demo http://jsfiddle.net/gasparilla/9cL7ua4r/11/
Can someone help me out?
The This keyword, specifies the caller of a function, in this case the button the user clicked on. From there on, you can change the properties of the element using the This keyword.
Here's a quick reference: https://www.w3schools.com/js/js_this.asp
var likeIcon = document.querySelectorAll(`.table__like-icon`);
for (var icon of likeIcon) {
icon.addEventListener('click', likeIconIsClicked);
}
function likeIconIsClicked() {
this.classList.toggle(`table__like-icon_active`);
}
.table__like-icon_active {
background-color: blue!important;
}
.table__like-icon {
background: red;
height: 50px;
width: 50px;
//your custom class including background-image: ,...
}
<button class="table__like-icon" type="button"></button>
<button class="table__like-icon" type="button"></button>
<button class="table__like-icon" type="button"></button>
Alternatively, you could use forEach that could remember the icon reference in every loop.
var likeIcons = document.querySelectorAll(`.table__like-icon`);
likeIcons.forEach(icon => { // change from `for` to `forEach`
icon.addEventListener('click', function() { // change from 'onclick' to 'click'
icon.classList.toggle(`table__like-icon_active`);
});
})
.table__like-icon{
width: 21px;
height: 18px;
margin: auto 22px auto auto;
background-repeat: no-repeat;
background-size: contain;
box-sizing: border-box;
background-color: red;
border: 0 none;
outline: 0;
padding: 0;
}
.table__like-icon:hover{
opacity: 0.5;
cursor: pointer;
}
.table__like-icon_active{
opacity: 1;
background-color: black;
}
<section class="table">
<div class="table__element">
<img
src="./images/kirill-pershin-1088404-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">FirstButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="./images/kirill-pershin-1404681-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">SecondButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="./images/kirill-pershin-1556355-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">ThirdButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="./images/kirill-pershin-1404681-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">forthButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="images/kirill-pershin-1556355-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">fifthButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="./images/kirill-pershin-1088404-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">sixthtButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
</section>
I guess you looking for a way to detect which button click and perform operations on that button
here you go
document.addEventListener('click', (event) => {
if (!event.target.matches('.table__like-icon')) return;
// do what ever you want to do
// event is your desire clickable button event.
event.target.style.backgroundColor = "black";
e.preventDefault();
})

Change styles to toggled divs

Im using filtered divs and I want to change the flex-direction of each section only when that specific section is toggled, then go back to original styles when going back to "Show all"
Here is the link for the filtered divs
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_elements
The W3 Schools code is not very good. It can be improved greatly but the use of data attributes, proper event listeners and event bubbling
All we need to to to get your "flex switch" happening is add/remove a class to the ".container" to indicate if filtered or not
var container = document.querySelector(".container");
//Add an event listener to the div containing the buttons
document.getElementById("myBtnContainer").addEventListener("click", function(event) {
//remove active class from previous active button
this.querySelector(".active").classList.remove("active");
//add active class to clicked item
event.target.classList.add("active");
//Add filitered to ".container" if "All" clicked, remove otherwise
container.classList.toggle("filtered", event.target.dataset.target !== "all")
//Display chosen elements
var elements = container.querySelectorAll(".filterDiv");
for (var i = 0; i < elements.length; i++) {
//Long version of below
//var categoryArray = elements[i].dataset.category.split(",");
//var hasTargetCategory = categoryArray.includes(event.target.dataset.target);
//elements[i].classList.toggle("show",hasTargetCategory);
elements[i].classList.toggle("show", elements[i].dataset.category.split(",").includes(event.target.dataset.target));
}
})
.filterDiv {
background-color: #2196F3;
color: #ffffff;
width: 100px;
line-height: 100px;
text-align: center;
margin: 2px;
flex: none;
}
.container {
margin-top: 20px;
display: flex;
flex-wrap: wrap;
}
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 12px 16px;
background-color: #f1f1f1;
cursor: pointer;
}
.btn:hover {
background-color: #ddd;
}
.btn.active {
background-color: #666;
color: white;
}
/*Class to change flex direction*/
.filtered {
flex-direction: column;
}
/*Hide elements without the show class*/
.filtered>.filterDiv:not(.show) {
display: none;
}
<div id="myBtnContainer">
<button class="btn active" data-target="all"> Show all</button>
<button class="btn" data-target="cars"> Cars</button>
<button class="btn" data-target="animals"> Animals</button>
<button class="btn" data-target="fruits"> Fruits</button>
<button class="btn" data-target="colors"> Colors</button>
</div>
<div class="container">
<div class="filterDiv" data-category="cars">BMW</div>
<div class="filterDiv" data-category="colors,fruits">Orange</div>
<div class="filterDiv" data-category="cars">Volvo</div>
<div class="filterDiv" data-category="colors">Red</div>
<div class="filterDiv" data-category="cars,animals">Mustang</div>
<div class="filterDiv" data-category="colors">Blue</div>
<div class="filterDiv" data-category="animals">Cat</div>
<div class="filterDiv" data-category="animals">Dog</div>
<div class="filterDiv" data-category="fruits">Melon</div>
<div class="filterDiv" data-category="fruits,animals">Kiwi</div>
<div class="filterDiv" data-category="fruits">Banana</div>
<div class="filterDiv" data-category="fruits">Lemon</div>
<div class="filterDiv" data-category="animals">Cow</div>
</div>
I didn't understand what you meant by "flexible steering", would it be to replace the phrase "Show all" with the active section? This can be done with jquery, but you would have to replace the element that houses the text.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="all">Show all</button>
<button type="button" id="cars">cars</button>
<script>
$("#cars").on("click", function(){
$("#all").text('Cars');
});
$("#all").on("click", function(){
$("#all").text('Show All');
});
</script>
Alternative without jquery
<button id="all">Show All</button>
<button id="cars" onclick="cars()">Cars</button>
<script>
function cars() {
document.getElementById("all").innerHTML = "Cars";
}
</script>
Alternative to build the tab without so much javascript and css
Bootstrap Collapse: You can use Bootstrap Colapse which already has a structure ready and you would only have to organize the HTML with the divs as per the documentation: https://getbootstrap.com/docs/4.0/components/collapse/
Javascript behavior: Like the previous one, this is a tabbed browsing API, which is identical to the code you are using, with the difference that here you would be using the Bootstrap structure and will not require many modifications, you should note the similarity between this and the previous one, in fact what changes is only the usability, the situations in which you will use one or the other, but the purpose is the same, both seek to hide elements.
https://getbootstrap.com/docs/4.0/components/navs/#javascript-behavior

Proper div placement difficulties on 2x2 grid

this is a school project. Making a 2x2 grid, pictures in 3 of them and the picture should be able to be moved from "box to box". Everything else is in order, except the lower 2 divs.
The top 2 are perfectly in line, but when trying to make the second one, they either come right next to the first ones (with a br so they're a bit lower), or then on top of each other under the first 2. I know it's not a big thing that i'm missing, but i just can't seem to figure it out.
#loota {
float: left;
width: 200px;
height: 283px;
border: 2px solid #aaaaaa;
}
#loota2 {
float: left;
width: 200px;
height: 283px;
border: 2px solid #aaaaaa;
}
<div id="loota" ondrop="tiputus(event)" ondragover="siirto(event)">
<img id="kuva1" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=Placeholder&w=200&h=283" draggable="true" ondragstart="veto(event)" width="200" height="283">
</div>
<div id="loota" ondrop="tiputus(event)" ondragover="siirto(event)">
<img id="kuva2" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=Placeholder&w=200&h=283" draggable="true" ondragstart="veto(event)" width="200" height="283">
</div>
<br>
<div id="loota2" ondrop="tiputus(event)" ondragover="siirto(event)">
<img id="kuva3" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=Placeholder&w=200&h=283" draggable="true" ondragstart="veto(event)" width="200" height="283">
</div>
<div id="loota" ondrop="tiputus(event)" ondragover="siirto(event)"></div>
The 2x2grid can be created using css nth operators.
The drag and drop can be done on individual images with a class and an operator function:
(function closedScopeForDragAndDropImages() {
var dragTarget = null;
window.addEventListener("dragover", function(event) {
// prevent default to allow drop
event.preventDefault();
}, false);
window.addEventListener("drag", function(event) {
if (event.target.className == "dropable-image") {
dragTarget = event.target;
}
// prevent default to allow drop
event.preventDefault();
}, false);
window.addEventListener("drop", function(event) {
// prevent default action (open as link for some elements)
event.preventDefault();
// move dragged elem to the selected drop target
if (event.target.className == "dropable-image") {
var src = dragTarget.getAttribute("src");
dragTarget.setAttribute("src", event.target.getAttribute("src"));
event.target.setAttribute("src", src)
}
}, false);
})();
.tile {
float: left;
width: 200px;
height: 283px;
border: 2px solid #aaaaaa;
}
.tile:nth-child(2n+3) {
clear: left;
}
<div class="tile">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=Placeholder1&w=200&h=283" class="dropable-image" draggable="true" />
</div>
<div class="tile">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=Placeholder2&w=200&h=283" class="dropable-image" draggable="true" />
</div>
<div class="tile">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=Placeholder3&w=200&h=283" class="dropable-image" draggable="true" />
</div>
<div class="tile">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=Placeholder4&w=200&h=283" class="dropable-image" draggable="true" />
</div>

How to hide div when it's already open?

I couldn't think of any better title, so I will try to explain my question here as clear as possible. I'm quite a newbie in JQuery so this is probably a very easy question.
I have some divs with a button on it. When you click the button, another div should pop-up.
My question is: How can I make the div, which is already open, close when clicking on another button?
I made a fiddle with some example code: http://jsfiddle.net/zuvjx775/1/
And the example code here:
HTML:
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="1" value='click!' />
</div>
<div class="show_1">
</div>
</div>
<br>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="2"value='click!' />
</div>
<div class="show_2">
</div>
</div>
JQuery:
$('.showDiv').on('click', function(){
var id = $(this).attr('id');
$('.show_'+id).show();
});
When show_1 for example is visible, and I click on the button in div2, I want show_2 to come up, which it does, but show_1 to dissapear.
Can someone point me in the right direction?
You can hide all divs that their class starts with 'show' before show the one you want. For example:
$('.showDiv').on('click', function() {
var id = $(this).attr('id');
$("div[class^='show']").hide();//find div class starts with 'show' and hide them
$('.show_' + id).show();
});
.test {
border: 1px solid black;
height: 100px;
width: 450px;
float: left;
}
.show_1 {
width: 50px;
height: 50px;
background-color: yellow;
float: left;
display: none;
}
.show_2 {
width: 50px;
height: 50px;
background-color: green;
float: left;
display: none;
}
.wrapper {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="1" value='click!' />
</div>
<div class="show_1">
</div>
</div>
<br>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="2" value='click!' />
</div>
<div class="show_2">
</div>
</div>
Is the structure of the document fixed?
is so... I guess the easiest way of doing this is to just do the following:
$('.showDiv').on('click', function(){
var id = $(this).attr('id');
if(id == 1){
$('.show_1').show();
$('.show_2').hide();
}else{
$('.show_2').show();
$('.show_1').hide();
}
})

Categories