My JavaScript if...else statement isn't working properly - javascript

So I'm fairly new to javascript, and I'm trying to use a simple if...else statement to toggle between showing and hiding a div element. My HTML page looks like this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<style type="text/css">
#fluffy {
height:200px;
width:200px;
background-color:yellow;
display:block;
}
#pepper {
height:200px;
width:200px;
background-color:green;
display:block;
}
</style>
</head>
<body>
<div id="fluffy"></div>
<div id="pepper" onclick="changeState()"></div>
<script type="text/javascript">
function changeState() {
var divState = document.getElementById('fluffy').style.display;
if (document.getElementById('fluffy').style.display == 'block') {
document.getElementById('fluffy').style.display = 'none';
}
else if (document.getElementById('fluffy').style.display == 'none') {
document.getElementById('fluffy').style.display = 'block';
} else {
alert('test error message');
}
}
</script>
</body>
</html>
When I load the page in my browser, I receive an alert box containing 'test error message'. My original code had document.getElementById('fluffy').style.display stored in a variable called divState, but this didn't even give me an alert box, it didn't do anything. I get the feeling I'm using == wrong or something, but I'm really not sure. I've used ===, and when that didn't work I switched to ==, which is in the code above.
If anyone knows what exactly I'm doing wrong, I would appreciate the help.
Thanks, Harold

Alright, it looks like you guys fixed my problems. I can't thank you enough, and I will definitely look into jQuery!

Try changing the onclick to be this
<div id="pepper" onclick="changeState"></div>

document.getElementById('fluffy').style.display is ''. Since you're setting styles with a stylesheet, you'll have to use getComputedStyle (plus friends for cross-browser compatibility). You can find an example cross-browser implementation in the answer to Get all computed style of an element.

I know, you're trying to learn JavaScript what I also want to encourage, but with jQuery, this whole stuff would be a one-liner plus crossbrowser-friendly etc.
<div id="fluffy"></div>
<div id="pepper"></div>
The <script> contains just:
$("#pepper").click(function () { $("#fluffy").toggle(); });
Try it out at JSFiddle.

When the page first loads, the div doesn't have any inline styles. element.style reads inline styles only.
You will need to render the div with style="display:block;" or if you can't/don't want to do that, look into getComputedStyle options for your supported browsers

Use computed style:
<div id="fluffy"></div>
<div id="pepper" onclick="changeState()"></div>
<script type="text/javascript">
function changeState() {
var fluffy = document.getElementById('fluffy');
var divState = window.getComputedStyle(fluffy).display;
if (divState == 'block') {
fluffy.style.display = 'none';
}
else if (divState == 'none') {
fluffy.style.display = 'block';
} else {
alert('test error message');
}
}
</script>
jsFiddle

Related

How do I pass a string variable through this java script function and then into getElementById()?

My objective is to create a function that can be called at different points on a page to make certain <p> elements disappear and reappear. The viewer will be able to click on key words in the paragraph to make elements below it appear.
I have done something similar in another code block, but it requires me to make a new function every time I use it. And I may potentially have 15-20 times I need to call it on one page.
Below is the code I have written. The "state" is what I am using to make sure the processor is getting into my loops. I've had some experience with Java but I'm not super knowledgeable so I need small things like this.
This works perfectly, but only for one time. Because I have to set the variable "hidden" as the specific id of the object I want, it makes it a single use kind of thing. That would mean I need multiple functions. I would like to just pass the name of the id into the function as a parameter so that the function could be called for different objects.
<!doctype html>
<html>
<head>
<style>
a {color: red; }
</style>
</head>
<body>
<p id="currentState">Not set yet</p>
<p>Within this paragraph, <a onclick="myFunction()">THIS</a> is what you click.</p>
<p id="hidden1">This is supposed to be hidden</p>
<script>
var state;
function myFunction() {
var hidden = document.getElementById("hidden1");
if (hidden.style.display != "none"){
hidden.style.display = "none";
state = "State: Visible";
}
else if (hidden.style.display == "none"){
hidden.style.display = "block";
state = "State: Hidden";
}
document.getElementById("currentState").innerHTML = state;
}
</script>
</body>
</html>
And here is what I keep trying to do to fix my problem, but nothing seems to work. I'm not sure if its because the getElementById() doesn't recognize my variable as a string or if I'm not declaring the parameter correctly.
<!doctype html>
<html>
<head>
<style>
a {color: red; }
</style>
</head>
<body>
<p id="currentState">Not set yet</p>
<p>Within this paragraph, <a onclick="myFunction("hidden1")">THIS</a> is what you click.</p>
<p id="hidden1">This is supposed to be hidden</p>
<script>
var state;
function myFunction(name) {
var hidden = document.getElementById(name);
if (hidden.style.display != "none"){
hidden.style.display = "none";
state = "State: Visible";
}
else if (hidden.style.display == "none"){
hidden.style.display = "block";
state = "State: Hidden";
}
document.getElementById("currentState").innerHTML = state;
}
</script>
</body>
</html>
I think something is off in this line:
<a onclick="myFunction("hidden1")">THIS</a>
That seems to be when my program says I have a syntax error. I'm not sure what that is. Any help is greatly appreciated!
<a onclick="myFunction("hidden1")">
The first " starts the value of the HTML attribute.
The second " ends the value of the HTML attribute.
If you want a " as data in an attribute delimited with " then you have to use an entity such as ".
Alternatively, switch to using '.
Better yet, bind your event handlers using JavaScript. That will separate your markup from your logic and save you from some of the weirdness that is intrinsic event attributes.
Here's an answer using jQuery:
In your html:
... THIS ...
... <p id="hidden1"> ...
In your JavaScript:
$('.hiddenTrigger').click(function () {
var target = $(this).data('target');
$('#'+target).show();
});

Conditionally blink text

Can anyone let me know how can i make it blink text based on if statement?
Sample:
if value 0 - NO BLINK
If not 0 - Should blink
Thank you in advance
I think you mean $('.blink'), assuming you mean a class and not a tag name.
<script type="text/javascript">
setInterval(function(){
$('.blink').each(function(){
$(this).css('visibility' , $(this).css('visibility') === 'hidden' ? '' : 'hidden')
});
}, 250);
</script>
JSFiddle test
You don't need the inline style, Since you are using jQuery, toggle will help you doing this. you can simply do it in this way.
Here is demo:
setInterval(function(){
$('.blink').toggle();
}, 250);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class='blink'>Hello!</div>
<div class="blink">Testing again.</div>
See this fiddle.
http://jsfiddle.net/tcy6a5kz/
//Line 21
if (blinkStatus == 1) {
Blinker.start();
}
else {
Blinker.stop();
}
At this line, you can change the if statement to whatever you want (true-like or false-like value).
You can get the span value like this:
// This will return the inner text of the span
// I expect this text as 0 or more. (number or text)
// No text in the span == 0
$('span.top-title').val();
So you can change my code at line 21:
//Line 21
if ($('span.top-title').val() == 1) {
Blinker.start();
}
else {
Blinker.stop();
}
NOTE: You need jQuery included to your site to run this code. Everything starting with '$' is jQuery object and cannot operate without jQuery library.
In case you do not have jQuery. You can include it in your HTML:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
This script must be included before the scripts that uses jQuery. (in most cases it's included at the <head> tag of the HTML. I'm not sure, but I think the "blog service providers" ignoring script definitions in the blog posts.
I know this is too old, but it might help someone searching for this.
I figure it out myself and I know that this is not the best solution.
<div class="blink1">
<span><asp:Label runat="server" Text="Label" ID="inprogress"></asp:Label></span>
</div>
<div class="blink2"><span><asp:Label runat="server" Text="Label" ID="behindsched"></asp:Label></span>
</div>
<script>
var in_progress = parseInt(documentElementById("<%=inprogress.ClientID%>").innerHTML);
var behind_sched = parseInt(documentElementById("<%=behindsched.ClientID%>").innerHTML);
var blinkfunc1 = function(){
$('.blink1').toggle();
}
var blinkfunc2 = function(){
$('.blink2').toggle();
}
var blinkspeed = 550;
$(document).ready(function{
if(in_progress > 0){
setInterval(blinkfunc1, blinkspeed);
}
if(behind_sched > 0){
setInterval(blinkfunc2, blinkspeed);
}
});
</script>
Make sure you don't forget this into your head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

How can show pop when user typing using javascript?

I want to create a function for showing pop or status when user typing something in field, I want to do it without submitting form, I have try following function but its not working properly can anyone let me know where the problem..........?
Javascript
<script type="text/javascript">
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
function checkFile(e) {
if ($('#confirm').val().length > 0) {
alert("txt");
}
}
</script>
HTML
<input type="text" name="text" id="confirm">
Just listen to the onkeyup and onkeydown events. I included a jsfiddle that might help.
jsfiddle
Edit - The Latest Update
Okay, I see you've got your fiddle from Vivek, but you might be interested in this as well. Now I get completely what you want to achieve, and here's a short description. The best practice is to split JavaScript from HTML and avoid putting JavaScript inside HTML head and body as much as you can.
So, first create three files: Test.js Example.html and Test.css. Of course, you also need jQuery file which you just include here inside the head. In Example.html put the following code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="Test.css"/>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript" src="Test.js"></script>
</head>
<body>
<input type="text" id="test"/><span id="popup"></span>
</body>
</html>
In Test.css add some style to your pop-up span element (you could also use division element and style it to your liking if you want fixed height and width, add shadows and so on):
#popup {
background-color: red;
color: white;
display: none;
}
And finally, put the following JavaScript code in Test.js:
$(document).ready( function() {
$("#test").keyup( function() {
if($("#test").val().length>5) {
$("#popup").fadeIn();
$("#popup").html("Invalid length. Maximum is 5.");
}
else {
$("#popup").fadeOut();
}
});
});
By dividing JavaScript, CSS and HTML into separate files, you get much tidier HTML and separated styling and client-side logic from markup.
Old Answer
Wrap the code inside $(document).ready().
Like this:
$(document).ready(function() {
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
});
function checkFile(e) {
if ($('#confirm').val().length > 0) {
alert("txt");
}
}
Also, addEventListener is not available in IE8 and below. You could use the onchange event, like this:
$(document).ready(function() {
document.getElementById("confirm").onchange = checkFile;
});
There is a similar method for IE8 and earlier called attachEvent. In case of using the attachEvent method, it would look something like the following:
$(document).ready(function() {
document.getElementById('confirm').attachEvent('change', checkFile);
approveletter.attachEvent('change', checkFile);
});
You could also use the jQuery.change() as suggested in the comments by Protron:
$(document).ready(function() {
$("#confirm").change(function() {
if ($('#confirm').val().length > 0) {
alert("txt");
}
});
});
And of course it's possible to do it without the classic alert pop-up window. You could create your own HTML division element with display:none and show it when necessary. Just send me a note in the comments if you need instructions on that as well.
Using this, you need not click the web page.
<input type="text" name="text" id="confirm"><br /><br />
<span id="status" ></span>
<script type="text/javascript">
$('#confirm').keyup(function () {
if ($('#confirm').val().length > 0) {
$('#status').html("Text entered");
}
else
{
$('#status').html("Text removed");
}
}
)
</script>

Showing images conditionally

I've been working on a simple website for a while now. The basic coding and CSS are complete, so I am now looking to expand by adding certain features to the website. As it is a fully functioning website that serves a purpose, the main source of revenue comes from Google AdSense. I am looking for a way to show an image if Adblock is detected and another one if if it not.
The method I've found for detecting whether AdSense is active is shown below:
JS (saved as advertisement.js)
document.write('<div id="TestAdBlock" style="display:none;">an advertisement</div>');
The HTML bit:
<div id="adblockFrame">
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
if (document.getElementById("TestAdBlock") != undefined)
{
document.write('<strong>ADBlock Plus</strong> NOT detected!');
}
else
{
document.write('<strong>ADBlock Plus</strong> detected!');
}
</script>
</div>
CSS:
#adblockFrame {
visibility: hidden;
}
What I'm asking is that if someone could be kind enough to show me how, instead of displaying text, the JS would show an image in its place. I'm not that good with JS so I'm grateful for any help.
I would create an empty target div :
<div id="adblockDetector"></div>
<script type="text/javascript">
if (document.getElementById("TestAdBlock") != undefined)
{
document.getElementById('adblockDetector').innerHTML="<img src='noadblock.jpg' alt='no adblock' />";
}
else
{
document.getElementById('adblockDetector').innerHTML="<img src='adblock.jpg' alt='Adblock detected!' />";
}
</script>
Assuming you are using jquery, just because you tagged it:
html
<div id="wheretoappend"></div>
js
var whereToAppend = '#wheretoappend';
var myDiv = $('<div/>', {id: 'mydiv'});
($('#adblockFrame').length)
? myDiv.addClass('hasit').appendTo(whereToAppend)
: myDiv.addClass('doesnt').appendTo(whereToAppend);
CSS
.hasit {background: url('hasit.png');}
.doesnt {background: url('doesnt.png');}
Please, don't use the devil document.write!
If you want to add content to your page, use DOM methods or .innerHTML.
If you want to detect AdBlock, just create a global variable in advertisement.js
For example:
advertisement.js:
window.TestAdBlock = true;
Your page:
<div id="adblockFrame">
<img id="TestAdBlock" alt="AdBlock Detected???" />
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
(function() {
var AdBlockImg = document.getElementById('TestAdBlock');
if (window.TestAdBlock)
{
AdBlockImg.src = "/images/AdBlockDetected.jpg";
AdBlockImg.alt = "AdBlock Detected!";
}
else
{
AdBlockImg.src = "/images/AdBlockNOTDetected.jpg";
AdBlockImg.alt = "AdBlock NOT Detected!";
}
AdBlockImg.title = AdBlockImg.alt;
});
</script>
</div>
Firstly, you shouldn't use document.write for anything. It's just bad practice. But here's generally how I'd do it with jquery, since you tagged it:
<div id="adblockFrame>
<script type="text/javascript" src="js/advertisement.js"></script>
<script type="text/javascript">
var adsAllowed = adsAllowed || false;
var src = adsAllowed ? '/images/myAd.png' : '/images/noAd.png';
$('#ad').attr('src',src);
</script>
<img id="ad"/>
</div>
advertisement.js
var adsAllowed = true;

jquery get styles from an id

does anyone know how can i get all styles applied to an id using jquery (so i can reuse it later in another tag)? something like
css:
div#myid{
width:100px;
height:100px;}
so i can later do something like:
for (var parts in $('#myid').css())
alert ('all parts of the style' + parts);
$('#myid').attr('class') returns a string of the classes.
You should be able to figure it out from here.
var classes = $('#myid').attr('class').split(' ');
for(var c in classes)
{
alert(classes[c]);
}
It is not jquery but works well:
var style = window.getComputedStyle(document.getElementById('myid'), null);
alert(style.color);
You can replace document.getElementById('myid') by $('#myid').get(0) if you really want to use jquery here.
This works either for a style given by CSS or directly applied on the element with the style attribute.
Not sure.. I had tried attr('class') before and it returned empty. trying now again produces the same result (nearly). i suppose attr('class') in jquery isnt exactly the same as styles defined via id. try running this, let me know if you get different results please:
<html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
alert($('#myid').attr('class')); // returns 'empty'
var classes = $('#myid').attr('class').split(' ');
for(var c in classes){
alert(c); // returns 0
}
});
</script>
<style>
#myid {
width:100px;
height:100px;
background:red;
}
</style>
<body>
<div id="myid"></div>
</body>
</html>

Categories