Trying to get jQuery to change a different img src when clicked - javascript

I've got 2 seperate divs that change background img src when clicked which works fine, but I would like it to change the other image its present with. E.g. div 1 is pressed and becomes "open", if div2 is "open" it then becomes closed. My jQuery is rather limited and have it functioning where it can change the image, but need to figure out how to apply the "closed" class to images that haven't just been clicked. Ideally it would use the attr() so I can add more later.
jQuery
$(".box").on("click", function() {
// need to make this function select the other div.
if ($(this).hasClass("closed")) {
$(this).addClass("open").removeClass("closed");
} else {
$(this).addClass("closed").removeClass("open");
}
var id = $(this).attr("data-id");
$(this).toggleClass("open");
$(".hideDivs").hide();
$("#" + id).show();
});
.container {
width: 640px;
height: 450px;
background-color: #eee;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
}
.text-primary {
font-size: 14px;
text-align: center;
margin-bottom: 5px;
}
.box {
cursor: pointer;
width: 90px;
height: 180px;
display:block;
margin:auto;
background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
}
.open {
background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/open_ihcmuz.png");
}
.closed {
background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
}
.hideDivs {
display: none;
}
.panel-body {
padding: 10px;
margin-top: 5px;
}
.title {
font-weight: bold;
font-size: 14px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="box" data-id="divId1">
</div>
</div>
<div class="col-xs-6">
<div class="box" data-id="divId2">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default hideDivs" id="divId1">
<div class="panel-body">
<span class="title">Practices for safe packaging of cooked foods</span>
<ul>
<li>Label and date all food.</li>
<li>Package high-risk food in small batches for refrigeration and return to refrigerated storage as soon as possible (within 20 minutes).</li>
<li>Store packaging products in a clean environment and protect from contamination.</li>
</ul>
</div>
</div>
<div class="panel panel-default hideDivs" id="divId2">
<div class="panel-body">
<span class="title">Practices for safe freezing of cooked foods</span>
<ul>
<li>When packaging food for freezing, cover or wrap, label and date (production and freezing date) all foods.</li>
<li>Freeze food in small quantities to ensure food is frozen quickly.</li>
<li>Do not overload freezer units and ensure air can circulate.</li>
<li>Do not freeze foods that have been cooked then refrigerated and reheated.</li>
</ul>
</div>
</div>
</div>
</div>
</div>

Please check the jsfiddle and let me know if you are looking something like this.
https://jsfiddle.net/314sybno/2/
$(".box").on("click", function() {
var id = $(this).attr("data-id");
if( id === 'divId1') {
$('div[data-id="divId2"]').addClass('closed').removeClass('open');
} else {
$('div[data-id="divId1"]').addClass('closed').removeClass('open');
}
// need to make this function select the other div.
if ($(this).hasClass("closed")) {
$(this).addClass("open").removeClass("closed");
} else {
$(this).addClass("closed").removeClass("open");
}
$(".hideDivs").hide();
$("#" + id).show();
});

This might be a better approach:
$(".box").on("click", function() {
// Hide all detail divs
$(".hideDivs").hide();
if ($(this).is(".closed")) {
// Close other open boxes
$(".box.open").removeClass("open").addClass("closed");
// Open this box and show the corresponding details div
$(this).removeClass("closed").addClass("open");
var id = $(this).attr("data-id");
$("#" + id).show();
} else {
// Close this box
$(this).removeClass("open").addClass("closed");
}
});
Also, I would recommend changing your HTML to have your 'box' elements also have a 'closed' class, so you do not repeat/need the CSS background attribute on the 'box' class.
See it working on this fiddle

Related

I want to add forEach so that I can active each & everydiv separately

I have a section & it's reaction section with love, comment & share option. so I want to add toggle Class whenever I click on love button or comment button and I make it
but the problem is I copy this section for multiple time then it's not work, I use try to use foreach, but it's not work.
I want it link no matter how many same section on my page, if I click any of this button, the toggle things work
this is the code I use , it's the HTML code
this is the code
document.querySelector(".lverct").addEventListener("click", () => {
document.querySelector(".lverct").classList.toggle("kp");
});
document.querySelector(".cmnt").addEventListener("click", () => {
document.querySelector(".cmnt").classList.toggle("kp");
});
document.querySelector(".Share").addEventListener("click", () => {
document.querySelector(".Share").classList.toggle("kp");
});
document.querySelector(".lverct1").addEventListener("click", () => {
document.querySelector(".lverct1").classList.toggle("kp");
});
document.querySelector(".cmnt1").addEventListener("click", () => {
document.querySelector(".cmnt1").classList.toggle("kp");
});
document.querySelector(".Share1").addEventListener("click", () => {
document.querySelector(".Share1").classList.toggle("kp");
});
.pstfeedbackbtn{
margin:10px 20px;
display:flex;
gap:10px;
}
.dflx{
cursor:pointer;
}
.lverct.kp button{
background:crimson;
}
.lverct1.kp button{
background:crimson;
}
.cmnt.kp button{
background:green;
}
.cmnt1.kp button{
background:green;
}
.Share.kp button{
background:orange;
}
.Share1.kp button{
background:orange;
}
<div class="pstfeedbackbtn">
<div class="dflx lverct ">
<button>Like</button>
</div>
<div class="dflx cmnt ">
<button>Comment</button>
</div>
<div class="dflx Share ">
<button>Share</button>
</div>
</div>
<div class="pstfeedbackbtn">
<div class="dflx lverct lverct1">
<button>Like</button>
</div>
<div class="dflx cmnt cmnt1">
<button>Comment</button>
</div>
<div class="dflx Share Share1">
<button>Share</button>
</div>
</div>
I don't want to make it like this, I want to make it like a for-each functionality so that no matter how many same section I have, I'll work for everyone
You can get all three button types with the selector .dflx > button in a querySelectorAll, then loop through them and use e.target.parentElement to get the div to toggle the class on.
Since you're now attaching the click events to button, e.target.parentElement will always find the .dflx div, as long as the HTML structure doesn't change (see event bubbling and capturing). It's in my opinion a little cleaner since the button element is what the user is intending to click:
Array.from(document.querySelectorAll(".dflx > button")).forEach(el => {
el.addEventListener("click", (e) => {
e.target.parentElement.classList.toggle("kp");
});
});
.pstfeedbackbtn {
margin: 10px 20px;
display: flex;
gap: 10px;
}
.dflx {
cursor: pointer;
}
.lverct.kp button {
background: crimson;
}
.cmnt.kp button {
background: green;
}
.Share.kp button {
background: orange;
}
<div class="pstfeedbackbtn">
<div class="dflx lverct ">
<button>Like</button>
</div>
<div class="dflx cmnt ">
<button>Comment</button>
</div>
<div class="dflx Share ">
<button>Share</button>
</div>
</div>
<div class="pstfeedbackbtn">
<div class="dflx lverct lverct1">
<button>Like</button>
</div>
<div class="dflx cmnt cmnt1">
<button>Comment</button>
</div>
<div class="dflx Share Share1">
<button>Share</button>
</div>
</div>

Check to see of current clicked element equals to previous clicked element-Javascript

I have a list of items displayed in a container with a dropdown associated with every container.A snippet of how the container list looks:
http://jsfiddle.net/jHpKB/2/
When I click on the button , the dropdown menu shows up, however, when I try to click on any other button button, the dd stays and does not hide. the list is dynamically created. What I was trying to do is if the current clicked element is same as that of the previous clicked elemnt, then hide the first dd menu
Is there way to check if a clicked element is equal to the previous clicked element in javascript(no jquery)
code:
afterRender: function() {
this.el.on('click', function(e) {
//here i want to check (if e.getTarget() === secondClickedEment) { //do something}
},this);
}
is this possible?
Thanks
You can test object equality with jQuery using the is function. Requires 1.6 or higher.
var stuff = $('#stuff');
var thing = stuff;
if (stuff.is(thing)) {
// the same
}
So for your situation this should work:
afterRender: function() {
this.el.on('click', function(e) {
var clickedElm = $(e.getTarget());
var secondElm = $(secondClickedElm);
if (clickedElm.is(secondElm)){
// same elements
}
},this);
}
jQuery example:
use var lastClicked; to hold the last clicked element, then each click check if the same one clicked then reset the lastclicked, otherwise update the lastclicked.
var lastClicked;
$('.container').on('click', function(e) {
if (this == lastClicked) {
lastClicked = '';
$(this).children('.menu').hide();
} else {
lastClicked = this;
$('.menu').hide();
$(this).children('.menu').show();
}
});
.container {
border: 1px solid #333;
height: 300px;
width: 200px;
float: right;
margin-right: 20px;
}
.menu {
display: none;
}
.button {
border: 1px solid #333;
background: #333;
float: right;
height: 20px;
width: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="button">
</div>
<div class="menu">
<div class="option1 option">option1</div>
<div class="option2 option">option2</div>
</div>
</div>
<div class="container">
<div class="button">
</div>
<div class="menu">
<div class="option1 option">option1</div>
<div class="option2 option">option2</div>
</div>
</div>
<div class="container">
<div class="button">
</div>
<div class="menu">
<div class="option1 option">option1</div>
<div class="option2 option">option2</div>
</div>
</div>
One way to do this would be to dynamically add/remove a class to the div, indicating if it's open or not. Then on click, you could just toggle that class.
Example:
let containers = document.getElementsByClassName('container');
for (let i=0; i<containers.length; i++) {
let button = containers.item(i).getElementsByClassName('button')[0];
let menu = containers.item(i).getElementsByClassName('menu' )[0];
button.addEventListener('click', function() {
menu.classList.toggle('open');
});
}
Then in your CSS:
.open {
display: block;
}

Multiple show/hide buttons with button text change on click

i have a wordpress page with several buttons, that show/hide a certain div, also the button text changes from "more info" to "less info" according to button click.
This is my code so far, but as i have multiple buttons, of course each time i click on one, the code is executed for all hidden divs and button texts.
What has the code to be like, that it only affects the one button actually clicked / hidden div at a time?
Heres the HTML:
<a class="clicker reveal" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;">MORE INFOS</a>
and JS:
<script type="text/javascript">
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery(".slider").hide();
jQuery('.reveal').click(function() {
if (jQuery(this).text() === 'MORE INFOS') {
jQuery(this).text('LESS INFOS');
} else {
jQuery(this).text('MORE INFOS');
}
});
jQuery(".clicker").click(function(){
jQuery(".slider").slideToggle("slow");
jQuery.each(masterslider_instances, function(i, slider) {
slider.api.update();
slider.api.__resize(true);
jQuery.each(slider.controls, function( index, control ) {
if (control.realignThumbs) control.realignThumbs();
});
jQuery.each(masterslider_instances, function(a,b){
b.api.update(true);
});
});
});
});
</script>
and the targeted div:
<div class="slider>Some content</div>
Thank you in advance!
UPDATE
I am informed that the button is in a div, the update reflects that small change:
From:
var tgt = $(this).next('.slider');
To:
var tgt = $(this).parent().next('.slider');
The following demo uses the class methods. Details are provided within the source in the comments.
SNIPPET
/*
Removed a chunk of meaningless code
since there's no way of using it
because the plugin isn't
provided (I'm assuming).
*/
$(function() {
/*
Combined both the `more/less` and
`slideToggle()` features under one
class(`.reveal`) and one click event.
*/
$('.reveal').on('click', function(e) {
/*
Prevent anchor from default behavior
of jumping to a location.
*/
e.preventDefault();
/*
See if `.reveal` has class `.more`
*/
var more = $(this).hasClass('more');
/*
`.tgt` is the next `.slider` after
`this`(clicked `a.reveal`).
*/
var tgt = $(this).parent().next('.slider');
/*
Toggle `.reveal`'s state between `.more` and
`.less` classes. (See CSS)
*/
if (more) {
$(this).removeClass('more').addClass('less');
} else {
$(this).removeClass('less').addClass('more');
}
/*
`slideToggle()` only the `div.slider` that
follows `this` (clicked `a.reveal`)
*/
tgt.slideToggle('slow');
});
});
.reveal {
display: block;
}
.reveal.more:before {
content: 'MORE INFO';
}
.reveal.less:before {
content: 'LESS INFO';
}
.slider {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div>
<a class="reveal more" href="" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;"></a>
</div>
<div class="slider">Some content</div>
<div>
<a class="reveal more" href="" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;"></a>
</div>
<div class="slider">Some content</div>
<div>
<a class="reveal more" href="" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;"></a>
</div>
<div class="slider">Some content</div>
Try this
jQuery('.reveal').each(function(idx,item) {
jQuery(item).click(function(){
if (jQuery(this).text() === 'MORE INFOS') {
jQuery(this).text('LESS INFOS');
}
else {
jQuery(this).text('MORE INFOS');
}
});
});
Here is working Fiddle
Make a reference between the anchor and div by using data attribute.
<a class="clicker reveal" data-target="slider-1" style="background-color: #81d742; border: 0px; font-size: 12px; text-decoration: none;">MORE INFOS</a>
<div class="slider slider-1">Some content</div>
Now, you can do the following-
jQuery('.clicker').click(function() {
var targetDiv = jQuery('.' + jQuery(this).attr('data-target'))
if (jQuery(this).text() === 'MORE INFOS') {
jQuery(this).text('LESS INFOS');
targetDiv.slideDown('slow');
} else {
jQuery(this).text('MORE INFOS');
targetDiv.slideUp('slow');
}
// do the rest of your stuff here
});

combine two sets of floats on click

I have a folio page. When a user clicks link 'design' - all the relevant design images are shown. When the user clicks 'art' all the relevant art images are shown
What I would like to have is an 'all' button which combines them all.
The two sets are contained in divs which turn on and off perfectly in the below javascript. What I need is to add to the script so there is a function that says - click all and display both, instead of one or the other.
When have them both turned on, they flow into each other fine so thats not an issue. I'll keep the code as brief as I can. I have only icluded one image in each section but there is actually 6-7.
Thanks in advance!
my html is:
<div class="sectiondivider">
<div id="ThumbLinks">
ALL
ART<br />
GD
</div>
</div>
<div class="thumb_container">
<div class="thumbs" id="gd_info">
<div class="flex_one">
<img class="icon-image" src="gd.jpg"/>
</div>
</div>
<div class="thumbs" id="art_info">
<div class="flex_one">
<img class="icon-image" src="art.jpg"/>
</div>
</div>
</div>
CSS:
.gd_thumbs {
display:none;
}
.art_thumbs {
display:none;
}
.icon-image {
width:100%;
height:auto;
opacity:1;
}
.flex_one {
width:28%;
float:left;
position:relative;
background-color:#000;
border: solid 2px rgb(0,81,88);
overflow:hidden;
margin-left:4%;
margin-top:4%;
}
Javascript
$('#ThumbLinks a').click(function(e) {
// do something fancy
return false; // prevent default click action from happening!
e.preventDefault(); // same thing as above
});
$(document).ready(function(){
$("div.thumbs:gt(0)").hide(); // to hide all div except for the first one
$('#ThumbLinks a').click(function(selected) {
var getID = $(this).attr("id");
var projectImages = $(this).attr("name");
$("div.thumbs").hide();
$("#" + getID + "_info" ).fadeIn( "slow" );
});
});
Try this snippet.
It just checks if the link's id is all to show them all and, if not, keeps on with your old code. I tried to keep it as short as possible.
EDIT: I think the effect is nicer if, first of all, you hide them all
$('#ThumbLinks a').click(function(e) {
// first we hide them all (for a nicer effect)
$("div.thumbs").hide();
if ($(this).attr("id") == "all")
// if the ThumbLink's id is 'all' we fade in all the divs
$(".thumbs").fadeIn("slow");
else
// if not, we fade in just the correct one
$("#" + $(this).attr("id") + "_info").fadeIn("slow");
});
$(document).ready(function() {
$("div.thumbs:gt(0)").hide(); // hide all div except for the first one
$('#ThumbLinks a').click(function(e) {
// fisrt we hide them all (for a nicer effect)
$("div.thumbs").hide();
if ($(this).attr("id") == "all")
// if the ThumbLink's id is 'all' fade in all the divs
$(".thumbs").fadeIn("slow");
else
// if not, we fade in just the correct one
$("#" + $(this).attr("id") + "_info").fadeIn("slow");
});
});
.thumbs {
color: white;
}
.gd_thumbs {
display: none;
}
.art_thumbs {
display: none;
}
.icon-image {
width: 100%;
height: auto;
opacity: 1;
}
.flex_one {
width: 28%;
float: left;
position: relative;
background-color: #000;
border: solid 2px rgb(0, 81, 88);
overflow: hidden;
margin-left: 4%;
margin-top: 4%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sectiondivider">
<div id="ThumbLinks">
ALL
ART
<br />
GD
</div>
</div>
<div class="thumb_container">
<div class="thumbs" id="gd_info">
<div class="flex_one">
I'm the GD div
<img class="icon-image" src="gd.jpg" />
</div>
</div>
<div class="thumbs" id="art_info">
<div class="flex_one">
I'm the ART div
<img class="icon-image" src="art.jpg" />
</div>
</div>
</div>

How to show and hide a div onMouseOver on top of another div

So right now I have 4 divs under the class "menubut"
I am trying to make a small overlay that shows when you hover over the menubut classes. I am also trying to get another div named "red" about a tenth of the size of the menubut to show when I hover over the class on the far left of the div.
[ Menubut ] //When Hovered over it should look like this
[(red) Menubut ] //< at the same time changing the background color of Menubut.
I'm fairly new to Javascript so I'm not to sure how I would get started on this.
<div class = "menubut">
<div class = "red"></div>
</div>
<div class = "menubut">
<div class = "red"></div>
</div>
<div class = "menubut">
<div class = "red"></div>
</div>
<div class = "menubut">
<div class = "red"></div>
</div>
And my css for each looks like this:
.menubut
{
width: 90px;
padding-left: 23px;
padding-top: 5px;
}
.menubut:hover
{
background-color: rgba(0, 0, 255, 0.2);
}
.red
{
position: absolute;
background-color: red;
width: 15px; height: 15px;
}
If I can provide anymore info please let me know. Thank you
This is simple example, it can be done much more efficient with jQuery (you should learn about this tool)
In this example if you hover above the little part, it will change color to blue, if you hover on the "regular" menubut, it will hover by the style you selected.
Html:
<div class="menubut" id="menu1">
<div class="red" onmouseover="doSomething('menu1')" onmouseout="clearBackground('menu1')"></div>
</div>
<div class="menubut" id="menu2">
<div class="red" onmouseover="doSomething('menu2')" onmouseout="clearBackground('menu2')"></div>
</div>
<div class="menubut" id="menu3">
<div class="red" onmouseover="doSomething('menu3')" onmouseout="clearBackground('menu3')"></div>
</div>
<div class="menubut" id="menu4">
<div class="red" onmouseover="doSomething('menu4')" onmouseout="clearBackground('menu4')"></div>
</div>
JS:
function doSomething(id) {
var ele = document.getElementById(id);
ele.style.backgroundColor = 'blue';
}
function clearBackground(id) {
var ele = document.getElementById(id);
ele.style.backgroundColor = '';
}
Working fiddle

Categories

Resources