jQuery - clicking 1 div and change class on 2 divs - javascript

I have 2 divs named yellowUp with up arrows as background images.
As it is now, when I click on a yellowUp div, only the clicked div changes class. How do I make both divs change class on click?
HTML
<div class="yellowUp"></div>
<div class="yellowUp"></div>
<div id="contentContainer"></div>
CSS
.yellowUp {
background-image: url(../images/arrow-up.png);
}
.clicked {
background-image: url(../images/arrow-down.png);
}
jQuery
$(".yellowUp").click( function(event){
event.preventDefault();
if ( $(this).hasClass("clicked") ) {
$("#contentContainer").stop().animate({marginTop:"0px"}, 200);
} else {
$("#contentContainer").stop().animate({marginTop:"-300px"}, 200);
}
$(this).toggleClass("clicked");
return false;
});

If you want both .yellowUp divs to have the .clicked class when 1 is clicked, then instead of doing $(this).toggleClass("clicked"); just select the class instead.
jQuery
$(".yellowUp").toggleClass("clicked");
$(".yellowUp").click( function(event){
event.preventDefault();
if ( $(this).hasClass("clicked") ) {
$("#contentContainer").stop().animate({marginTop:"0px"}, 200);
} else {
$("#contentContainer").stop().animate({marginTop:"-300px"}, 200);
}
$('.yellowUp').toggleClass("clicked");
return false;
});
.yellowUp {
color: blue;
}
.clicked {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="yellowUp">Hi</div>
<div class="yellowUp">Hi</div>
<div id="contentContainer">BLah</div>

it's because you only change the class of the clicked object.
instead, use :
$(document).ready(function(){
$('.yellowUp').on('click', function(e){
e.preventDefault();
$('.yellowUp').each(function($key, $index) {
if ( $(this).hasClass("clicked") ) {
$("#contentContainer").stop().animate({marginTop:"0px"}, 200);
} else {
$("#contentContainer").stop().animate({marginTop:"-300px"}, 200);
}
$(this).toggleClass("clicked");
});
});
});
In the previous code we parse each element with the class yellowUp to toggle clicked.
hopes it helps !
Nic

You need to change this toggleClass to select ".yellowUp"

Thanks Nic,
I went with this really simple option (to me at least):
$(".yellowUp").click( function(event){
event.preventDefault();
if ( $(this).hasClass("clicked") ) {
$("#contentContainer").stop().animate({marginTop:"0px"}, 200);
$(".yellowUp").css("background-image", "url(images/arrow-up.png)");
} else {
$("#contentContainer").stop().animate({marginTop:"100px"}, 200);
$(".yellowUp").css("background-image", "url(images/arrow-down.png)");
}
$(this).toggleClass("clicked");
return false;
});
I just added a css background image change for each condition.

Related

Can I use a condition inside a toggleClass based on the toggle status

I am creating a toggle and need to execute a command based on the toggle status.
When I click .flip1 first time it adds the flipped class to .card1.
I also want it to show an alert "flipped added"
When I click it again it removes the flipped class and I want it to show an alert "flipped removed".
I imagine that the code will look something like this:
$(document).ready(function () {
$('.flip1').click(function () {
$('.card1').toggleClass('flipped');
if ("class added"){
alert("flipped added");
}
if ("class removed"){
alert("flipped removed");
}
});
});
Is there something I can put in the if to know whether the toggle is true or false?
This can be achieved via jQuery's hasClass() method like so:
$(document).ready(function() {
$('.flip1').click(function() {
$('.card1').toggleClass('flipped');
// use hasClass to see if .card1 has .flipped class now applied.
// if true, that indicates it was just added
if ($('.card1').hasClass('flipped')) {
alert("flipped added");
} else {
alert("flipped removed");
}
}
);
});
.flipped {
background:yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="card1">
Card1 (yellow if flipped)
</div>
<a href="#" class="flip1">
Flip1
</a>
You can use addClass() and .removeClass() to change class and .hasClass() to check the state.
Here is your code :
$(document).ready(function () {
$('.flip1').on('click', function () {
if ( $('.card1').hasClass('flipped') ) {
$('.card1').removeClass('flipped');
alert("flipped removed");
} else {
$('.card1').addClass('flipped');
alert("flipped added");
}
});
});
$(document).ready(function () {
$('.flip1').on('click', function () {
if ( $('.card1').hasClass('flipped') ) {
$('.card1').removeClass('flipped');
alert("flipped removed");
}
else {
$('.card1').addClass('flipped');
alert("flipped added");
}
});
});

Toggle div when clicked and hide when clicked outside

I already have my code to toggle show and hide the div but whenever I try to add the Hide when clicked outside, it conflicts the toggle code, I need to toggle the div_menu but also hides it when clicked outside just like the facebook drop down menu
$(document).ready(function() {
$(".toggle_menu").click(function(e) {
$(".div_menu").toggle();
e.preventDefault();
});
});
You can do something like
$(document).ready(function () {
$(".toggle_menu").click(function (e) {
$(".div_menu").toggle();
e.preventDefault();
});
$(document).click(function(e){
if(!$(e.target).closest('.toggle_menu, .div_menu').length){
$(".div_menu").hide();
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="toggle_menu">toggle_menu</button>
<div class="div_menu">
<div>some random content menu</div>
</div>
<div style="height: 100px; background: lightgrey;">some other content goes here</div>
use e.target to find the current targeted element ,and using is() Check the current matched set of elements against a selector
$(document).ready(function () {
$(document).click(function (e) {
if ($(e.target).closest(".toggle_menu,.div_menu").length) {
$(".div_menu").toggle();
e.preventDefault();
} else {
$(".div_menu").hide();
}
});
});
DEMO
$("body").click
(
function(e){
if ($(e.target).is($(".toggle_menu"))) {
$(".div_menu").toggle();
}else{
$(".div_menu").hide();
}
}
);
try this
$(document).click(function(e){
if($(e.target).parents('.div_menu').length == 0 && $(e.target).attr('class') != "div_menu"){
$(".div_menu").toggle();
}
});
$(document).ready(function() {
$(".toggle_menu").click(function(e) {
$(".div_menu").toggle();
e.preventDefault();
});
$(document).click(function(e) {
$(".div_menu").hide();
});
});

JS/jQuery Change CSS with if/else statement

I'm trying to change the background image of a div using an if/else statement after a user clicks a part of the page. With the code below, the div will collapse as intended, however the accompanying background image does not change.
$(document).ready(function() {
$(".titles-us").click(function() {
$(".map-us").toggle();
$(".map-tri").hide();
$(".map-can").hide();
$(".map-eur").hide();
if ($(".us-icon").css('background-image') === 'url("public/images/collapse-lg.png")') {
$(".us-icon").css({
'background-image' : 'url("public/images/expand-lg.png")'
});
}
else {}
});
});
You can always addClass() with jQuery. Add a class when the user clicks the element. And give that class a background attribute different from the background of the element without that class.
if ($(".us-icon").hasClass('collapsed') == false) {
$(".us-icon").addClass('collapsed');
}
// If you want to remove the background on second click:
else {
$(".us-icon").removeClass('collapsed');
}
In your css, you can add this:
.collapsed {
background-image: url("public/images/expand-lg.png")
}
You can have a setup like this adding/referring to a class
$(document).ready(function() {
$(".titles-us").click(function() {
$(".map-us").toggle();
$(".map-tri").hide();
$(".map-can").hide();
$(".map-eur").hide();
if ($(".us-icon").hasClass('img-collapse'){
$(".us-icon").removeClass('img-collapse').addClass('img-expand');
}
else{
$(".us-icon").removeClass('img-expand').addClass('img-collapse');
}
});
});
and in your CSS:
.img-collapse{
background-image : url("public/images/collapse-lg.png");
}
.img-expand{
background-image : url("public/images/expand-lg.png");
}
I'm not entirely sure why your original code isn't sufficing, but here's a working example you can use to compare:
$(".us-icon").on('click', function() {
var myEl = $(this);
var bgimg = myEl.css('background-image');
if( bgimg === "url(http://placehold.it/200x200)" ) {
myEl.css({ 'background-image' : 'url(http://placehold.it/100x100)' });
} else {
myEl.css({ 'background-image' : 'url(http://placehold.it/200x200)' });
}
});
( fiddle )

hover/click with list of DIVs

I've a set of DIVs and I need to give them a effect on mouse hover and when one of DIVs being clicked, the clicked DIV should look like it's being hovered (or whatever effect) until another DIV get clicked.
<div class="items" id="item1">AN ITEM</div>
<div class="items" id="item2">AN ITEM</div>
<div class="items" id="item3">AN ITEM</div>
<div class="items" id="item4">AN ITEM</div>
I've tried to achieve this using jQuery but the effect goes away on mouse out.
$('.items').hover(function () {
var div = $(this).attr('id');
if ($(div).css("background-color") == settings.color2) {
return false;
} else {
$("#" + div).css("background-color", settings.color2);
}
}, function () {
var div = $(this).attr('id');
if ($(div).css("background-color") == settings.color2) {
return false;
} else {
$("#" + div).css("background-color", "transparent");
}
}).click(function () {
$(this)
.closest('div')
.css("background-color", "transparent");
$(this).css("background-color", settings.color2);
});
Instead of adding the hover styles using JS, I would suggest adding them via CSS. And add the same styles to an "active" class and toggle that class on click.
Something like this:
CSS:
.items:hover,
.items.active {
background-color: /* whatever */;
}
JS:
$('.items').on('click', function() {
$('.items').removeClass('active');
$(this).addClass('active');
});
Try adding an "active" class on click which has the same styles as hover. When some other div is clicked you remove that class from previously clicked div and add it to the current div.
Try
var $items = $('.items').hover(function () {
$(this).css("background-color", 'red');
}, function () {
if (!$(this).hasClass('clicked')) {
$(this).css("background-color", "transparent");
}
}).click(function () {
$items.filter('.clicked').css("background-color", "transparent").removeClass('clicked')
$(this).addClass('clicked').css("background-color", 'red');
});
Demo: Fiddle
Note: I din't use a class to style the clicked state because it looks like the background color is coming from an option, in that case it will be difficult to assign a class, else the clicked class also needs to be passed as a setting.
A better alternative will be to
var settings = {
color2: 'red',
clicked: 'clicked'
}
var $items = $('.items').hover(function () {
$(this).css("background-color", settings.color2);
}, function () {
if (!$(this).hasClass('clicked')) {
$(this).css("background-color", "transparent");
}
}).click(function () {
$items.filter('.' + settings.clicked).removeClass(settings.clicked)
$(this).addClass(settings.clicked);
});
Demo: Fiddle

Adress checkbox of class switch but only with the id light2

my problem is the following:
I styled my Checkboxes on my WebSite with this IMG / CSS / jQuery Code
The interesting part is this:
<script type="text/javascript">
$(document).ready(function() {
// Iterate over checkboxes
$("input[type=checkbox].switch").each(function() {
// Insert mark-up for switch
$(this).before(
'<span class="switch">' +
'<span class="mask" /><span class="background" />' +
'</span>'
);
// Hide checkbox
$(this).hide();
// Set inital state
if (!$(this)[0].checked) {
$(this).prev().find(".background").css({left: "-56px"});
}
}); // End each()
// Toggle switch when clicked
$("span.switch").click(function() {
// If on, slide switch off
if ($(this).next()[0].checked) {
$(this).find(".background").animate({left: "-56px"}, 200);
// Otherwise, slide switch on
} else {
$(this).find(".background").animate({left: "0px"}, 200);
}
// Toggle state of checkbox
$(this).next()[0].checked = !$(this).next()[0].checked;
});
}); // End ready()
</script>
Now I want to access:
<input type="checkbox" id="light2" class="switch">
How do I have to adress the ID Tag with JavaScript?
I tried something like this:
<script>
$(document).ready(function(){
$("span.switch + #light2").click(function(){
if($(this).next()[0].checked)
{
alert('checked');
}
else
{
alert('unchecked');
}
});
});
</script>
Thanks for any hint
$(document).ready(function(){
$("#light2").click(function(){
if($("#light2").is(":checked"))
{
alert('checked');
}
else
{
alert('unchecked');
}
});
});
Working Example: http://jsfiddle.net/bA2fX/
If your intent is to style every .switched element, you should do it via CSS.
If your needs are more complex then you can do it by selecting every .switch class element using $('.switch'). For example:
$('.switch').css('color', 'red');
Instead, to select specific elements with an ID (since it must be unique) you can simply to use $('#light2'). For example:
$('#light1').on( 'click', function( evt ) {
evt.preventDefault();
if ($(this).is(':checked')) {
/* your AJAX code */
}
});
$('#light2').on( 'click', function( evt ) {
evt.preventDefault();
if ($(this).is(':checked')) {
/* your AJAX code */
}
});
However, since part of your code is created at runtime by jQuery, you'll have to style and attach events (well, for this last you could also delegate) at the end of the onDomReady pseudo-event, otherwise your code won't find the requested elements.
Thanks to ClarkeyBoy, the solution is:
<script>
$(document).ready(function(){
$("#light2").prev("span.switch").click(function() {
if($("#light2").attr("checked"))
{
alert('checked');
}
else
{
alert('unchecked');
}
});
});
</script>

Categories

Resources