javascript loop not working? - javascript

i want to know length of a tags
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++) {
alert(x[i].length)
}
}
</script>
</head>
<body>
first
second
third
<input type="submit" onclick="clickme()"/>
</body>

Since value is not a standard property of a link, you will probably need to use .getAttribute("value"):
var x = document.getElementsByTagName('a');
for (var i=0; i<x.length;i++){
alert(x[i].getAttribute("value"));
}

In this example, x[i] is a anchor DOM Element object. It doesn't have a value property normally. However, if you want to use the property, you can access it via:
x[i].getAttribute('value');
Personally, I would use HTML5 data attributes and define the anchor like:
one
Then access the value via:
x[i].getAttribute('data-value');
If a HTML5 doctype is used, this will be valid.

I'm confused, you've changed your original question code sample from:
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++) {
alert(x[i].value) //<- "value" not a valid property on the anchor tag
}
}
</script>
to
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++) {
alert(x[i].length) //<- "length" not a valid property on the anchor tag
}
}
</script>
If you're just trying to determine what the ordered number of that anchor tag itself is, you could just use "i" (and again - var it!):
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for( var i=0;i<x.length;i++) {
alert(i);
}
}
</script>
Or am I missing something that you're asking?

jfriend00 got that right.
I thought I'd also point out though that you might want to declare "i" either ahead of, or inline with your for. Otherwise you're using a global "i" that could have unexpected consequences elsewhere.

Related

Change a div background image using javascript if/else

I am trying to get the background image of a div to change at an interval. I created an Array with the images, and every few seconds the function should check the value of "x" against the array length. If X is less, x will increase by one and the background image will change to the next image in the array, otherwise it will set x=0 and restart the process.
The div and initial image shows up how I want, but nothing happens.
I know there are probably better ways to do this, but I am very new to Javascript and want to learn why this code doesn't work. Thanks in advance for the help!!
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ImageChanger</title>
<style type="text/css">
#imagediv {
float:left;
border-style:ridge;
border-width:8px;
border-color:Green;
border-radius:15px;
width:1250px;
height:450px;
background-image:url(images/landscape1.jpg)
}
</style>
<script type="text/javascript">
function displayNextImage() {
var x;
If (x<imageArray.length) {
x=x+1;
document.getElementById("imagediv").style.backgroundImage=images[x];
}
else {
x=0;
document.getElementById("imagediv").style.backgroundImage=images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var imageArray=new Array();
images[0] = "images/landscape1.jpg";
images[1] = "images/landscape2.jpg";
images[2] = "images/landscape3.jpg";
images[3] = "images/landscape4.jpg";
</script>
</head>
<body>
<div id="imagediv">
</div>
</body>
</html>
If (x<imageArray.length) {..
should be
if (x<imageArray.length) {
Javascript is case-sensitive.
Also you have some missing braces like you are not closing
function displayNextImage() { ....
Use your browser console to debug. These syntax errors will be shown there.
As far as syntax issues go:
As #Zee stated, If should be lowercase (if)
Also, as #Zee and some others stated, you are not closing function displayNextImage() { with a closing brace }.
You are improperly defining the background-image property in your function, whereas you defined it correctly in the block of CSS. You must wrap the image name with url().
You are never calling your timeout function, startTimer.
You create a new array imageArray but then use an undeclared array images

Trying to change button's contents each hit fails

Given the code :
<html>
<head>
<script src="jquery-2.1.0.min.js"></script>
Something...
</head>
<button id='flip' type='button'>Flip</button>
<script>
$('#flip').bind('click', function() {
var x = document.getElementById("flip").name;
if (x == 'Flip')
{
$(this).text('Flop');
}
else
{
$(this).text('Flip');
}
});
</script>
</body>
</html>
I'm trying to change the button each time it is clicked , but it doesn't work .
Any idea how to fix it ?
Much appreciated
There is no name attribute on your <button>, so you'll always get empty value. No need for document.getElementById because button is in this. Simply call text() without parameters to get current value:
var x = $(this).text();
Update
Here is demo in JsFiddler.
I would do something like this:
HTML:
<button id="flipflop">flip</button>
javascript:
var flip = true;
$("#flipflop").click(function(){
if(flip)
$("#flipflop").text("flop");
else
$("#flipflop").text("flip");
flip = !flip;
})
FIDDLE
edit: if you want to be really savvy, I would use the following line:
var flip = ($("#flipflop").text() === "flip");
Which automatically determines which way you need to flip (or is it flop?).

Pass Variable to a Popup Window using Javascript

I need to pass some text from the current page to a popup window without going for a server hit. The information (herewith represented by 90) is already available in the parent form (it's like a paragraph-long text which is stored in a hidden variable). I just need to display that as a popup.
Here's what I've tried, this works to some extent but doesn't work if I pass text, instead of a number. My second concern is that the solution kinda looks ugly. Any tips? Thank you.
This is SCCE, you can run it straight in your machine.
<html>
<head>
<title>A New Window</title>
<script type="text/javascript">
var newWindow;
var data;
function makeNewWindow(param) {
data = param;
if (!newWindow || newWindow.closed) {
newWindow = window.open("","sub","status,height=200,width=300");
setTimeout("writeToWindow()", 50); /* wait a bit to give time for the window to be created */
} else if (newWindow.focus) {
newWindow.focus( ); /* means window is already open*/
}
}
function writeToWindow() {
var k = data;
alert(data);
var newContent = "<html><head><title>Additional Info</title></head>";
newContent += "<body><h1>Some Additional Info</h1>";
newContent += "<scr"+"ipt type='text/javascript' language='javascript'> var localVar; localVar = "+ k +"; document.write('localVar value: '+localVar);</scr"+"ipt>";
newContent += "</body></html>";
// write HTML to new window document
newWindow.document.write(newContent);
newWindow.document.close( ); // close layout stream
}
</script>
</head>
<body>
<form>
<input type="button" value="Create New Window" onclick="makeNewWindow('90');" />
</form>
</body>
</html>
Actually, I googled and saw some other approach that uses window.opener.document.forms.element, but here, the window has to know in advance what it has to read from the parent. I need to be able to pass it as it will vary:
<textarea rows="15" name="projectcontent" id="projectcontent" cols="87"></textarea>
<b>View Content</b>
<head>
<title>View Project Content</title>
</head>
<body>
<img src="/images/toplogo.jpg"><br/>
<script language="Javascript">
document.write(window.opener.document.forms['yourformname'].elements['projectcontent'].value)
</script>
<img src="/images/bottomlogo.jpg">
</body>
</html>
use window.opener
From Mozilla Developer Network:
When a window is opened from another window, it maintains a reference
to that first window as window.opener. If the current window has no
opener, this method returns NULL.
https://developer.mozilla.org/en-US/docs/Web/API/window.opener
This way you can have on your original window a callback, and you can notify the window it's load and ready, rather than wait a random delay...
you add a function on the original window:
window.popupReady = function (callbackToPopup) {
callbackToPopup(newData);
}
then the popup can tell the parent window it's ready and pass it a callback to update it with data..
and on the popup try something like:
window.dataReady(newData)
{
alert(newData);
}
document.addEventListener("load", function() { window.opener.popupReady (dataReady); }
I didn't test this code, but I would take such a path as this should ensure the popupWindow is ready for you and is along the spirit of JavaScript.
In your onclick attribute you pass '90' to the function, but the function isn't set up to take an argument. So, change the first line of your function like this:
function writeToWindow(data) {
You don't need the global var data; or the local var k = data;, so get rid of them.
And instead of + k + write + data +.
That should do get your data passed.
Use this code, it works perfectly in all browsers .
#desc = parent text area id
#desc_textarea = popup
$("#desc_textarea").val(window.opener.$("#desc").val())

Appending children into a popup-window. (JavaScript)

I'm having some trouble trying to get a fairly simple popupper to work. The idea is that the parent should open a popup window and then append a div in it.
The relevant parts of the code:
parent.html:
var childWindow;
function togglePref() {
childWindow = window.open("popup.html", "prefPopup", "width=200,height=320");
}
function loadPopupElements() {
var prefElements = document.getElementById("prefBrd").cloneNode(true);
var childDoc = childWindow.document;
var childLink = document.createElement("link");
childLink.setAttribute("href", "pop.css");
childLink.setAttribute("rel", "stylesheet");
childLink.setAttribute("type", "text/css");
childDoc.head.appendChild(childLink);
childDoc.body.appendChild(prefElements);
}
popup.html:
<head>
</head>
<body onload="opener.loadPopupElements();">
</body>
This works fine with Safari and Chrome, but for some reason IE refuses to append anything.
Ok, I managed to work around the problem with a uglyish solution using innerHTML. Apparently, as Hemlock mentioned, IE doesn't support appending children from a another document. Some suggested to take a look at the importNode() method but I seemed to have no luck with it either.
So, the workaround goes as follows:
parent.html:
var childWindow;
function togglePref() {
childWindow = window.open("popup.html", "prefPopup", "width=200,height=320");
}
function loadPopupElements() {
var prefElements = document.getElementById("prefBrd");
var childDoc = childWindow.document;
childDoc.body.innerHTML = prefElements.innerHTML;
}
popup.html:
<head>
<link href="pop.css" rel="stylesheet" type="text/css">
</head>
<body onload="loadElements();">
</body>
<script type="text/javascript">
function loadElements() {
opener.loadPopupElements();
}
</script>
This seems quite a nasty way to go because in my case the #prefBrd contains some input elements with dynamically set values, so in order for the popup.html to grab them, it has to do a bit of iteration at the end of the loadElements() function, which wouldn't have been necessary using appendChild.

MooTools/JavaScript variable scope

I am trying to make each number displayed clickable. "1" should alert() 80, "2" should produce 60, etc.
However, when the alert(adjust) is called, it only shows 0, not the correct numbers. However, if the commented out alert(adjust) is uncommented, it produces the correct number on page load, but not on clicking.
I was wondering why the code inside addEvents cannot access the previously defined variable adjust.
<html>
<head>
<script type="text/javascript" charset="utf-8" src="mootools.js"></script>
<script type="text/javascript" charset="utf-8">
window.addEvent('domready', function() {
var id_numbers = [1,2,3,4,5];
for(var i = 0; i<id_numbers.length; i++) {
var adjust = (20 * (5 - id_numbers[i]));
// alert(adjust);
$('i_' + id_numbers[i]).addEvents({
'click': function() {
alert(adjust);
}
});
}
});
</script>
</head>
<body>
<div id="i_1">1</div>
<div id="i_2">2</div>
<div id="i_3">3</div>
<div id="i_4">4</div>
<div id="i_5">5</div>
</body>
</html>
Thanks.
You are having a very common closure problem in that for loop.
Variables enclosed in a closure share the same single environment, so by the time the click callbacks are called, the for loop would have run its course, and the adjust variable will be left pointing to the last value it was assigned.
You can solve this with even more closures, using a function factory:
function makeClickHandler(adjust) {
return function() {
alert(adjust);
};
}
// ...
for(var i = 0; i<id_numbers.length; i++) {
var adjust = (20 * (5 - id_numbers[i]));
$('i_' + id_numbers[i]).addEvents({
'click': makeClickHandler(adjust)
});
}
This can be quite a tricky topic, if you are not familiar with how closures work. You may to check out the following Mozilla article for a brief introduction:
Mozilla Dev Center: Working with Closures

Categories