If else statement not reaching the else part - javascript

So I'm making a image-toggling function that can toggle between two images. More specifically, it toggles the background images of a div.
I'm using the jquery .data() function as a counter where one = first image and two = toggled image.
Here's the algorithm I'm using:
click button to start function.
When I click on the div, if the data is equal to "one", replace image and set data to "two".
When I click the image again, set the image back to the original image and set data equal to "one" so that the function can repeat itself.
It seems to replace the image on the first try, as in the first "if", but it doesn't replace the image again on the second try (the else part). It seems to never reach the else part, even though the first if should return false and then go to the else.
Any help will be appreciated. Also, I know there is a .toggle() function and other image-toggling methods, but I must use this one because this is only a small, edited chunk of a larger program.
Here's the code:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="mouseovertestlayout.css" />
<script>
function startEdit()
{
$("div").click(function ()
{
if (($(this).data('kangaroo')) == "one")
{
$(this).css('background-image', "url(image2.png)");
$(this).data('kangaroo',"two");
}
else
{
(this).css('background-image', "url(image1.png)");
$(this).data('kangaroo',"one");
}
});
}
</script>
</head>
<body>
<div class="container" data-kangaroo="one" ></div>
<button onclick="startEdit()"> </button>
</body>
</html>
Here's my .css
.container
{
width: 20px;
height: 20px;
line-height: 0;
border-style:solid;
border-width:1px;
border-color:red;
padding: 20px;
background-repeat:no-repeat;
background-image:url('image1.png');
}

You have a typo in your "else" first line is the $ missing at (this)

You are missing a $ in else clause.
Fixed:
function startEdit() {
$("div").click(function ()
{
if (($(this).data('kangaroo')) == "one")
{
$(this).css('background-image', "url(image2.png)");
$(this).data('kangaroo',"two");
}
else
{
$(this).css('background-image', "url(image1.png)");
$(this).data('kangaroo',"one");
}
});
}

Try like this
if (($(this).attr("data-kangaroo")) == "one") //Here is the edit
{
$(this).css('background-image', "url(image2.png)");
$(this).data('kangaroo',"two");
}
else
{
$(this).css('background-image', "url(image1.png)"); //Here put "$" before (this)
$(this).data('kangaroo',"one");
}

What you want to do can be done much shorter if you use a class and toggleClass.
Demo: http://jsbin.com/anazoq/1/edit
HTML:
<div class="container"></div>
<button>Toggle</button>
CSS:
div {
...
background: url(image1.png) no-repeat;
}
.switch {
background-image: url(image2.png);
}
JavaScript:
$('button').click(function() {
$('div').toggleClass('switch');
});

Related

Show div if another div has content

So I don't get why this isn't working. I want to show a Div when another div has a value. I got this code from stackoverflow and it's pretty simple. But it doesn't work for me. No console errors..
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').show();
}
});
If the html value of .txt is larger then 0 then show btn-01.
But it doesn't. In my web inspector it just says:
<div style="display: block;" class="btn-01"><p>Things</p></div>
If I remove the script it says:
<div class="btn-01"><p>Things</p></div>
So it does do something. I tried changing the show to hide. But no go.
<div style="display: none;" class="btn-01"><p>Things</p></div>
I tried:
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').addClass('showme);
}
});
btn-01 css:
.btn-01 {
background: #f60;
color: #fff;
border-radius: 2px;
padding: 5px;
text-align: center;
margin: 40px auto 0px auto;
width: 90%;
}
But that didn't work either. Does anyone know whats going on here?
Maybe I should work with an else statement? Help would be much appreciated.
JsFiddle
You need to either set the button to display none prior to the window loading or add an "else" statement to hide the element:
.btn-01{
display:none;
}
OR
$(document).ready(function(){
if ($(".txt").html().length > 0) {
$('.btn-01').show();
}
else
{
$('.btn-01').hide();
}
});
See the fiddle: https://jsfiddle.net/r89gg7tp/
IMPORTANT TO CONSIDER
If you have entered a line break between the starting and closing tags of the element, this will add to the length. You need to set the txt div to be in the following format:
<div class='txt'></div>
It may be better to change your function to this:
$(document).ready(function(){
if ($(".txt").html().trim(' ').length > 0) {
$('.btn-01').show();
} else {
$('.btn-01').hide();
}
});
This way you trim the whitespace before checking.
See the second fiddle: https://jsfiddle.net/r89gg7tp/3/
You need to hide the btn-01 with a "display:none" in the stylesheet and then execute your script.
I think you are having a "display:none !important" which is overriding the jquery show() function inline style.
This might help you.
$(document).ready(function(){
if (!$.trim($(".txt").html())){
$('.btn-01').addClass('showme');
}
});
Please let me know if you've any queries.
You can use .contents() with .toggle():
$(document).ready(function() {
$('.btn-01').toggle($(".txt").contents().length > 0);
});
.btn-01{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="txt">
<h3>Things Title</h3>
</div>
<div class="btn-01">
<p>Things</p>
</div>
You guys where all right. I needed to place the code in some Session file (Ajax). Now its working with the original code and even some that you provide.
Thanks!

bugged HTML code editor

$(document).ready(function() {
var btn = $('.gen');
btn.on('click', function() {
var areaTxt = $('.textarea').val();
var div = $('.result');
div.html(areaTxt);
});
});
.result {
border: 1px solid red;
width: 300px;
height: 150px;
}
.textarea {
width: 300px;
height: 150px;
}
<!DOCTYPE>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<textarea class="textarea"></textarea>
<input type="button" class="gen" value="generate">
<div class="result"></div>
</body>
</html>
I've created a simple HTML code editor. The problem is that when I add style for all classes or divs affect also to my code editor.
I want something like the editor of w3school. Just to show the result in iframe but all code in the textarea to affect only the result area.
http://jsfiddle.net/sederther/4x6dxrs5/
Add to your styles specifically for the box of results would not solve your problem?
.result p {
font-size:8px;
font-family:Georgia;
}
.result h1{
color:red;
font-size:26px;
font-family:Georgia;
}
Like this: http://jsfiddle.net/4x6dxrs5/2/
Check fiddle Here
Just did a few tweaking. Added a dummy attribute to 'textarea' and set a value for that attribute. I then loop through the element and check for the attribute, if found I will reset all the styles applied.
$(document).ready(function() {
var btn = $('.gen');
btn.on('click', function() {
var areaTxt = $('.textarea').val();
var div = $('.result');
div.html(areaTxt);
//Code Addtion
$("textarea").each(function(){
var attr =
$(this).attr('dataref');
if (typeof attr !== typeof undefined && attr !== false && attr == 'source') {
$(this).attr('style', 'background-color: #eee !important');
}
})
});
});
In this case, I am looping all the 'textareas' and check if it has 'dataref' attribute and the value equals source. if so then reset its style. I know it would be tedious to work on all the elements in similar manner, but without using iframe this can be work around.
my 2 cents

How can I make the image change based on the domain name visited? Using location.hostname

I have one website and two domain names. I want image "A" to appear if the visitor goes to
a page on www.SampleSiteA.com but image "B" should appear if on a page from www.SampleSiteB.com.
Unfortunately the result of my code below is blank, with no image appearing at all. Any ideas?
content for file: welcome.html
<html>
<head>
<script src="resources/js/domain.js" type="text/javascript"></script>
</head>
<body>
<div class="welcomepic"></div>
</body>
</html>
Content for file: styles.css
.picForA{
background-image: url('../img/A.png');
}
.picForB{
background-image: url('../img/B.png');
}
.welcomepic{
background-position:left center;
background-repeat: no-repeat;
padding-left:160px;
width:225px;
float:left;
height:100px;
display: block;
}
Content of file: domain.js
function welcomepic() {
if (location.hostname == 'www.SampleSiteA.com') {
$('.welcomepic').addClass('picForA');
} else {
$('.welcomepic').addClass('picForB');
}
}
you do not call your function. A solution would be to ad the following code to the head of the html.
$( document ).ready(function() {
welcomepic();
});
you also need to remove the previous set class in the welcompic function otherwise you'll end up with double classes.
function welcomepic() {
if (location.hostname == 'www.SampleSiteA.com') {
$('.welcomepic').removeClass('picForB').addClass('picForA');
} else {
$('.welcomepic').removeClass('picForA').addClass('picForB');
}
}

addClass Working But Not removeClass

I am trying to create a toggling highlight effect using addClass and removeClass.
<head>
<style>
.box-highlight {
border: 2px solid yellow;
}
</style>
<script type="text/javascript" src="javascript/vendor/jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#box').bind('click', function() {
if ($(this).hasClass('box-highlight')) {
$(this).removeClass('box-highlight');
}
$(this).addClass('box-highlight');
});
});
</script>
</head>
<body>
<div id="box" style="width: 100px; height: 100px; background-color: silver">
</div>
</body>
The addClass is working properly, but removeClass does not. I know there is a toggleClass method but I am just wondering what is wrong with this code.
You're removing the class, then adding it back with no delay, before the UI can be redrawn. You need to do one or the other, which suggests an else:
if ($(this).hasClass('box-highlight')) {
$(this).removeClass('box-highlight')
} else {
$(this).addClass('box-highlight')
}
The problem with your code is that it runs very quickly, and you won't see the effect :).
To make such effect, you can use a timer or delay. For example, you can do like this:
$("#box").addClass("box-highlight")
.delay(300).queue(function(next){
$(this).removeClass("box-highlight");
next();
});
Try this................
$(document).ready(function() {
$('#box').bind('click', function() {
if ($(this).hasClass('box-highlight')) {
$(this).removeClass('box-highlight');
}else{
$(this).addClass('box-highlight');
}
});
});

Adapt code inside dokuwiki spoilers style?

To change selector so it only show/hides when i click the image i put spoiler/ popdown menu directly after .OS image. Right now the popdown is a child of the .OS container, so clicks on it are passed to the .OS click handler.
But the code isn't perfect because when i click the 1st MAC both spoilers are opened.
But I want that spoilers are opened one at a time
But the main problem is that I can't fix the javascript code properly inside these types of spoilers (dokuwiki class) inside <td> tags:
This is the javascript code I use :
<div class="dokuwiki">
<div class="right_page">
<div class="entry-content">
<script type="text/javascript" src="./zzzz_files/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".nonjs").removeAttr( "href"); //href is needed for users without JS
$('.OS').click(function(){
if($(".details").is(":visible"))
{
$(".details").not(":hidden").hide("slow");
return true;
}
else
{
$(".OS").not(this).each(function(i) {
$(".details").hide("slow");
});
$(".details").show("slow");
return false;
}
});
});
</script>
<style type="text/css">
<!--
.details {
display: none;
clear: both;
padding: 2px;
}
.nonjs{
cursor:pointer;
}
img {
border: 0px;
}
-->
</style>
I thought about doing a video to better explain the problem and provide the local version of files for testing code:
Thanks in advance
This code works:
$(document).ready(function(){
$(".nonjs").removeAttr( "href");
//href is needed for users without JS
$('.OS').click(function(e){
if(!$(e.target).parents('.details').length){
if($(this).find('.details').is(":visible"))
{
$(this).find('.details').not(":hidden").hide("slow");
return true;
}
else
{
$(this).find('.details').show("slow");
return false;
}
}
});
});
I don't know what you're asking but here is what I think you want:
When clicking on an image, show the details below it and hide all others. If the details are already visible, hide them. Clicking something inside the details should not affect anything.
Demo
$(document).ready(function(){
$(".nonjs").removeAttr( "href"); //href is needed for users without JS
$('.OS').click(function(){
var details = $(this).next(".details");
$(".details").hide("slow");
if(details.is(":hidden")) {
details.show("slow");
}
});
});

Categories