Why do I get null when I getElementById? - javascript

I'm new to JS, and reading Javascript Dom, I'm trying to figure out one of the example in my book!
here is my html code
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="utf-8" />
<title>Image Gallery</title>
</head>
<body>
<script type = "text/javascript" src="showPic.js"></script>
<h1>Snapshots</h1>
<ul id = "image">
<li>
Fall
</li>
<li>
Sunshine
</li>
<li>
Green
</li>
<li>
Filter
</li>
</ul>
<img id = "placeholeder" src="images/rise.jpg" alt = "my image gallery"/>
<p id="description"> Choose an image</p>
</body>
</html>
here is my javaScript code
function showPic(whichPic) {
var source = whichPic.getAttribute("href");
var placeholder = document.getElementById("placeholeder");
placeholder.setAttribute("src", source);
description.firstChild.nodeValue = text;
}
var text = whichPic.getAttribute("title");
var description = document.getElementById("description");
function perpareGallery() {
var gallery = document.getElementById("image");
var links = gallery.getElementsByTagName("a");
for(var i = 0 ; i<links.length; i++) {
links[i].onclick = function() {
showPic(this);
return false;
}
}
}
my code didnt getting anything from id = image. and I checked many times dont know what is wrong....

There seems to be no code that actually runs the perpareGallery() function.
After you fix that, it might still not work if you run perpareGallery() before the elements in HTML (like your a elements) are parsed and rendered. So, you might want to do something like:
window.onload = prepareGalery;
Although there are way better ways to set-up events, this will run your function after all HTML is parsed.

Two advices on how to track down your issue:
1) All browsers have a so called javascript console. It shows you all syntax error with your code. For firefox and chromium the keyboard shortcut F12 turns it on/off
If you run your code and open the javascript console you'll see this error:
ReferenceError: whichPic is not defined
In your example it looks as if the line var text = whichPic.getAttribute("title"); belongs to the function showPic(whichPic), but it doesn't.
2) You should format your code to not get lost. Your current code formatted:
function showPic(whichPic) {
var source = whichPic.getAttribute("href");
var placeholder = document.getElementById("placeholeder");
placeholder.setAttribute("src", source);
description.firstChild.nodeValue = text;
}
var text = whichPic.getAttribute("title");
var description = document.getElementById("description");
function perpareGallery() {
var gallery = document.getElementById("image");
var links = gallery.getElementsByTagName("a");
for(var i = 0 ; i<links.length; i++) {
links[i].onclick = function() {
showPic(this);
return false;
}
}
}
If you now take a look to the formatted code, it no longer looks as if whichPic is used inside of showPic(whichPic) but outside of the scope. The error makes perfectly sense.
You might want to move it inside of the function, before you use it.

Related

The array won't work with the output of my pictures

I tried to show pictures with an array so I can change it per delay, kinda like a slideshow. The problem is, that only the first picture will load. when the counter of the array changes, the picture won't load.
The paths of the images are all correct
<!DOCTYPE html>`enter code here`
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test2</title>
<script>
var bilder = [];
var zeit = 3000;
var p = 0;
bilder[0] = "../Bilder/Bild1.jpg";
bilder[1] = "../Bilder/Bild2.jpg";
bilder[2] = "../Bilder/Bild3.jpg";
bilder[3] = "../Bilder/Bild4.jpg";
function BildAutoWeiter()
{
document.bild.src = bilder[p];
for( var i=0; i<= bilder.length; i++)
{
if(i <= bilder.length)
{
p++;
}
else
{
i = 0;
}
}
setTimeout("BildAutoWeiter()", zeit);
}
</script>
</head>
<body onload="BildAutoWeiter()">
<div>
<img name ="bild" width="100%" height="50%">
</div>
</body>
</html>
You need to use getElementsByName() to choose elements by their name=''. That returns an array of elements that use that name, so to choose a specific one, use an index [index] starting from 0. Do this instead:
document.getElementsByName('bild')[0].src = bilder[p];
That selects the first element that uses name='bild'
Also, the for statement is a bit useless. You could instead do:
function BildAutoWeiter()
{
document.bild.src = bilder[p];
p++;
setTimeout(BildAutoWeiter, zeit);
}
You don't need to put the function name in quotations and you can't have the parentheses while calling the function in setTimeout.

Trying to replace every href on the document

i'm completely new to Javascript and I wanted to create an Greasemonkey Script that replaced "/text/othertext/" to "/text2/text3" on all the href elements of the document. That's what i came up with, and as expected, it doesn't work:
var links = document.getElementsByTagName('a');
for (i=0; i<links.length; i++)
{
var gethref = links[i].getAttribute('href');
gethref = gethref.replace(/text\/othertext/g,'text2\/text3');
links[i].setAttribute("href", gethref);
}
Thanks in advance!
Edit: ok, i know why my script is not working, but i don't know if it can be fixed, i'm trying to replace elements that load after the page is completely loaded (maybe with ajax?)
http://i.imgur.com/7n5V7Bi.png
This code works. Your code looks okay too. Perhaps you are loading the script before the document elements? Note how my elements are listed before my script:
link
link
<script>
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
</script>
Edit, based on your comments a dirty fix to cause delay in your app before running a script is to use the setTimeout function. To delay five seconds for example, you might use it like this:
link
link
<script>
setTimeout(function() {
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
}, 5000); // < --- note the time in ms here
</script>
Not too sure why your code wouldn't be working.
I've put together the following snippet which might help.
(function() {
var anchors = document.querySelectorAll('a');
for(var i = 0; i < anchors.length; i++) {
var newHref = anchors[i].getAttribute('href').replace(/text\/othertext/g,'text2\/text3');
anchors[i].setAttribute('href', newHref);
}
}());
a {
display: block;
}
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>
If you run this snippet you'll see only one anchor is updated correctly as intended.
Hope that helps you out!
The easiest solution would be to wrap your code in this:
window.onload = function(){
/* your code here */
};
This will ensure that your code (especially if you've placed your script in the of the document, won't load until the whole page is loaded (including text, images, etc).
window.onload = function() {
document.body.innerHTML = document.body.innerHTML
.replace('<a href="text/othertext/"', '<a href="text2/text3"');
};
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>

autoclick link with javascript without id/class

got this example:
<html>
<head>
<script type="text/javascript">
function init(){
var linkPage = document.getElementById('linkid').href;
window.location.href = linkPage;
}
onload=init;
</script>
</head>
<body>
GO HERE
</body>
</html>
this script clicks the link "GO HERE". (works perfect)
but in my example i got no class or id in the link.
LINK NAME
is only thing that never change is the name of the link ("LINK NAME")
is it possible to search for "LINK NAME" and then click it like the working script above?
or something that will do what i need :D
JS has no way to search for a node by text contents (that I know of).
Array.prototype.forEach.call(document.getElementsByTagName('a'), function (elem) {
if (elem.innerHTML.indexOf('LINK NAME') > -1) {
window.location = elem.href;
}
});
Iterate over the links in the document and check the text:
for(var i = 0, len = document.links.length; i < len; i += 1) {
if(document.links[i].textContent === "LINK TEXT") {
document.links[i].click();
}
}
I'd just use the following bit, which uses jquery selection.
var link = $("a:contains('LINK TEXT')"); //get the a
var click = document.createEvent("Event"); //create event
click.initEvent("click", true, true);
link.dispatchEvent(click); // make it happen

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

css background image displays when user clicks link problem

I updated my post. Now it says "link is not defined" "thisLink[link].scopeObject = new Image();" It's important that the link remains though because it is a property of linkObj that holds the current link. I use the [] as a property rather than dot notation due to the looping ability it provides.
<script type="text/javascript">
window.onload = init;
var linkObj = new Object();
var listItems = new Object();
function init() {
for(var i=0; i < document.links.length; i++) {
var link = document.links[i];
linkObj[link] = link;
setupClick(linkObj);
}
}
function setupClick(thisLink) {
thisLink[link].scopeObject = new Image();
thisLink[link].scopeObject.src = thisLink[link].id + "Img.png";
thisLink[link].onclick = rollClick;
}
function rollClick() {
var list = document.getElementById("target").childNodes;
for(var i=0; i < list.length; i++) {
if(list[i].nodeName == "LI") {
var id = list[i] + i;
listItems[id] = id;
}
}
for(id in listItems){
if(listItems[id].indexOf(this[link].id) > -1) {
listItem[id].style.backgroundImage = this[link].scopeObject.src;
}
}
}
</script>
<ul id="target">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div id="mainContent">
<div id="navLinks">
<ul>
<li>Home</li>
<li>About</li>
<li>Products</li>
<li>Contact</li>
</ul>
I believe the trouble is in this line: var linkObj[link] = document.links[i];. You need to remove the var command at the front of that line. I presume your linkObj has been declared somewhere else in your code and you're attempting to insert a new value into it. If not, please post more complete code and I can look further into it.
-- EDITED BELOW --
Then my statement "I presume you defined linkObj elsewhere." is incorrect. You may need to go with this instead: var linkObj = document.links[i];. The var command creates variables. Once they're created, assignment does not require the var command. Are you attempting to keep an object that has reference to all of the links for later, or do you only need to use each link once? If the former, outside of your init() function add this line: var linkObj = {};.
-- MORE EDITS --
Holy Cow. I'm not 100% sure what your end aim here is, but I think you should use something like this at first:
<script type="text/javascript">
window.onload = init;
function init() {
for (var i = 0; i < document.links.length; ++i) {
setupClick(document.links[i]);
}
}
function setupClick(thisLink) {
thisLink.scopeObject = new Image();
thisLink.scopeObject.src = thisLink[link].id + "Img.png";
thisLink.onclick = rollClick;
}
</script>
That's going to get you to a point where you're at least assigning properties to the links as they exist in the document.links array. The desired behavior from your rollClick function is a little hazy to me, but at least using that to start out with you're assigning properties to the links in your page.

Categories

Resources