JS/jQuery Change CSS with if/else statement - javascript

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 )

Related

CSS toggler using Javascript

I want to toggle the white-space style of a tr element to normal when the tr is clicked. I've managed to take a function used for toggling colours and adapt this for my purposes, however I can only make the class change toggle once, and don't know how to change the this.style.background in line 3 to this.style.white-space, without breaking everything:
$(document).ready(function () {
$('tr').click(function () {
if(this.style.background == "" || this.style.background =="white") {
$(this).css('white-space', 'normal');
}
else {
$(this).css('white-space', 'nowrap');
}
});
});
I know this is fairly basic, however I've only started using JavaScript today, so if anyone could show me the solution and explain what needs to be done then I'd be very appreciative.
You just need to change the if condition so it depends on the value of white-space property:
$(document).ready(function () {
$('tr').click(function () {
var $this = $(this);
if($this.css('white-space') === 'nowrap') {
$this.css('white-space', 'normal');
}
else {
$this.css('white-space', 'nowrap');
}
});
});
You just need to use white-space for your ifstatements, and refactor those if statements. Fixed code below:
$(document).ready(function () {
$('tr').click(function () {
if($(this).css("white-space") == "nowrap") {
$(this).css('white-space', 'normal');
}
else {
$(this).css('white-space', 'nowrap');
}
});
});
Hopefully this helps!

jQuery - clicking 1 div and change class on 2 divs

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.

Why is removeclass not working when div is collapsed?

here is my fiddle
why when a div is clicked from another div does the arrow not appear back when the other div has collapsed? i have it set up so when the div does not have the class 'clicked' it then removes the class 'arrowhide' but it when you do the above it doesn't seem to remove the 'arrowhide' even though the div no longer has the class 'clicked' here is my code...
$(function timelinetiles() {
$('.timelineTile').click(function (evt) {
evt.stopPropagation();
$('.selected').children().not(this).removeClass('clicked');
$(this).toggleClass('clicked');
if ($('.selected').children().hasClass("clicked")) {
$('.details').addClass('show');
}
if ($('.timelineTile').hasClass("clicked")) {
$(this).children('.arrow').addClass('arrowhide');
} else {
$('.arrow').removeClass('arrowhide');
}
if ($('.selected').children().hasClass("clicked")) {
$(this).children('.header').height(430);
} else {
$('.header').height(80);
}
});
});
$(document).click(function () {
$('.timelineTile').removeClass('clicked');
$('.details').removeClass('show');
$('.arrow').removeClass('arrowhide');
});
Your line 4 also needs to remove the arrowhide class, like this:
$('.selected').children().not(this).removeClass('clicked')
.children('.arrow').removeClass('arrowhide');
Updated fiddle: http://jsfiddle.net/mcx0t0fh/2/
Alternatively, you could do away with the arrowhide business, and change your .arrow.arrowhide CSS rule to .clicked .arrow
Alternative fiddle: http://jsfiddle.net/mcx0t0fh/4/

coming back from a fadeOut in Jquery

In the following code, div's are faded out using the new fadeOut functionality of Jquery. Unfortunately, this changes the style of the tag to "display:none". And I can not figure out how to change it back, so that I can Fade it in.
I do not want to use the opacity style, or fadeTo, because I need the divs to be completely hidden, pulling all other floating divs up with it.
/* Hide interface, fade logo */
$('.toggle-ui').on({
'click': function (e) {
e.preventDefault();
var divToHide = ['#slideshow-nav', '#nav', '#content'];
$.each(divToHide, function(intValue, currentElement) {
// check alpha state and switch
var currVis = $(currentElement).css('visibility');
$(currentElement).css('visibility', currVis == 'visible'
? $(currentElement).fadeOut('slow')
: $(currentElement).fadeIn('slow'));
});
}
});
checking for the style "display" and using that for the conditional works.
As follows:
$('.toggle-ui').on({
'click': function (e) {
e.preventDefault();
var divToHide = ['#slideshow-nav', '#nav', '#content'];
$.each(divToHide, function(intValue, currentElement) {
// check alpha state and switch
var currDis = $(currentElement).css('display');
$(currentElement).css('visibility', currDis == 'none'
? $(currentElement).fadeIn('slow')
: $(currentElement).fadeOut('slow'));
});
}
});

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