7 Replies - 765 Views - Last Post: 14 May 2011 - 10:51 PM

#1 cRaZi_RiCaN  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 25-May 07

Javascript does not work in all pages.

Posted 14 May 2011 - 10:51 AM

I currently have some JS linked to my index.html in the <body> tags. The JS attaches some events to a <ol> for some image rollovers. It works fine in the index.html but as soon as I go to another page the JS says addEventListener is null. I included the JS in the <body> section in all the pages. I am using Chrome.

What are some common culprits? What should I be checking? Should I use jQuery?
Is This A Good Question/Topic? 0
  • +

Replies To: Javascript does not work in all pages.

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4353
  • View blog
  • Posts: 12,160
  • Joined: 18-April 07

Re: Javascript does not work in all pages.

Posted 14 May 2011 - 11:04 AM

You should be putting all javascript code that you intend to use on multiple pages in its own .js file and then link it into the file that way. Without seeing the code you have for index.html vs the other page, it is hard to say what you might be doing wrong.

You can use jQuery if you like, it is easy to learn and use but it is up to you. You can do it by hand or use jQuery depending on your needs.

Show us your code and perhaps we can help you figure out what is going wrong. If your page is public, provide the URL so we can also see it live in action.

Thanks! :)
Was This Post Helpful? 0
  • +
  • -

#3 cRaZi_RiCaN  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 25-May 07

Re: Javascript does not work in all pages.

Posted 14 May 2011 - 11:17 AM

This is the website: http://dl.dropbox.co...miZa/index.html

index.html code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
	<title>KmiZa!</title>
	<link rel="stylesheet" type = "text/css" href = "styles.css"/>
</head>
<body>
	<div id="navigation">
		<ol id = "navigation-buttons" >
			<li><a href = "index.html"><img id = "home-button" src = "Images/Home_Mouseout.png" alt = "Casa"/></a></li>
			<li><a href = "about.html"><img id = "about-button" src = "Images/AboutUs_Mouseout.png" alt = "Conocenos" /></a></li>
			<li><a href = "order.html"><img id = "order-button" src = "Images/Order_Mouseout.png" alt = "Pide tu KmiZa!" /></a></li>
			<li><a href = "gallery.html"><img id = "gallery-button" src = "Images/Gallery_Mouseout.png" alt = "Galeria" /></a></li>
			<li><a href = "contact.html"><img id = "contact-button" src = "Images/Contact_Mouseout.png" alt = "Contactanos" /></a></li>
			<li><a href = "twitter"><img id = "twitter-button" src = "Images/Twitter_Logo.png" alt = "Twiteanos" /></a></li>
			<li><a href = "facebook"><img id = "facebook-button" src = "Images/Facebook_Logo.png" alt = "Facebookeanos" /></a></li>
		</ol>
	</div>
	<div id="motto">
		<h1>Arte original para gente original.</h1>
	</div>
	<div id="slideshow-area">
		<img id = "slideshow-image" src = "image0.png" width = "515" height = "640" alt = "example photo" />
	</div>
	<div id = "slideshow-div">
		<ul id = "slideshow-navigation">
			<li id = "slideshow-previous">Previous</li>
			<li id = "slideshow-next">Next</li>
		</ul>
	</div>
	<div id="footer">
		Copyright &copy; 2011, Fernando Martinez
	</div>
	<script type = "text/javascript" src = "behavior.js"></script>
</body>
</html>


About.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
	<head>
		<title>About Us</title>
		<link rel="stylesheet" type = "text/css" href = "styles.css"/>
	</head>
	<body>
		<div id = "navigation">
			<ol id = "navigation-buttons" >
				<li><a href = "index.html"><img id = "home-button" src = "Images/Home_Mouseout.png" alt = "Casa" /></a></li>
				<li><a href = "about.html"><img id = "about-button" src = "Images/AboutUs_Mouseout.png" alt = "Conocenos" /></a></li>
				<li><a href = "order.html"><img id = "order-button" src = "Images/Order_Mouseout.png" alt = "Pide tu KmiZa!" /></a></li>
				<li><a href = "gallery.html"><img id = "gallery-button" src = "Images/Gallery_Mouseout.png" alt = "Galeria" /></a></li>
				<li><a href = "contact.html"><img id = "contact-button" src = "Images/Contact_Mouseout.png" alt = "Contactanos" /></a></li>
				<li><a href = "twitter"><img id = "twitter-button" src = "Images/Twitter_Logo.png" alt = "Twiteanos" /></a></li>
				<li><a href = "facebook"><img id = "facebook-button" src = "Images/Facebook_Logo.png" alt = "Facebookeanos" /></a></li>
			</ol>
		</div>
		<h1 id = "about-header">
			About Us:
		</h1>
		<p id = "about-info-paragraph">
			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris scelerisque turpis at tellus tristique a congue orci pulvinar. 
			Mauris malesuada gravida risus, venenatis mattis turpis vehicula quis. Praesent ullamcorper ipsum nec augue congue at tempus odio lobortis. 
			Suspendisse id accumsan orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris luctus, 
			risus et porta interdum, elit sapien molestie leo, a bibendum urna odio eu enim. In in sodales nulla. Fusce ultrices tortor vitae mauris viverra semper. 
			Nulla facilisi. Suspendisse nec imperdiet turpis. Quisque felis lorem, sollicitudin id ultrices id, dapibus a nisl. Pellentesque ac imperdiet mauris. 
			Fusce nec eros ligula. Nam ut nulla diam, ac bibendum turpis. Maecenas dapibus rhoncus nibh eget egestas. Cras tempor nulla justo, et ultricies nunc. 
			Nunc euismod ante sed eros porttitor vel tempor metus semper. Pellentesque viverra mollis massa quis tristique. Fusce eget metus arcu.
		</p>
		<div id="footer">
			Copyright &copy; 2011, Fernando Martinez
		</div>
		<script type = "text/javascript" src = "behavior.js"></script>
	</body>
</html>


JS code:

/**
 * @author Fernan
 */
/* Utilities */
function addEventSimple(element, eventType, functionName)
{
	if (element.addEventListener) 
	{
		element.addEventListener(eventType, functionName, false);
	} 
	else if (element.attachEvent) 
	{
		element.attachEvent('on' + eventType, functionName);
	}
}


function removeEventSimple(element, eventType, functionName)
{
	if (element.removeEventListener) 
	{
		element.removeEventListener(eventType, functionName, false);
	} 
	else if (element.attachEvent) 
	{
		element.detachEvent('on' + eventType, functionName);
	}
}

function hasClass(element, classToAdd)
{
	return element.className.match(new RegExp('(\\s|^)' + classToAdd + '(\\s|^)'));
}

function addClass(element, classToAdd)
{
	if (!hasClass(element,classToAdd))
	{
		element.className += " " + classToAdd;
	}
}

function removeClass(element, classToAdd)
{
	if (hasClass(element, classToAdd))
	{
		var reg = new RegExp('(\\s|^)' + classToAdd + '(\\s|^)');
		element.className = element.className.repLace(reg, ' ');
	}
}
/*end Utilities*/

/* My functions*/

function LoadImages ()
{
	var arrayLoader = new Array(3);
	
	//pre-load images
	for( var i = 0; i < arrayLoader.length ; i++)
	{
		arrayLoader[i] = "image" + i + ".png";
	}
	return arrayLoader;
}

function NextImage()
{
	if (arrayCounter < imageSources.length - 1)
	{
		arrayCounter++;
		image.src = imageSources[arrayCounter];
	}	
}

function BackImage()
{
	if (arrayCounter > 0)
	{
		arrayCounter--;
		image.src = imageSources[arrayCounter];
	}
}

function ChangeButtonImageMouseOver()
{
	/* Naming convention for button images when mouseovered: [name][_][mouseover/mouseout].[png]*/
	var substring = this.src.split("_");
	this.src = substring[0] + "_" + "Mouseover" + "." + photoExtension;
}

function ChangeButtonImageMouseOut()
{
	/* Naming convention for button images when mouseovered: [name][_][mouseover/mouseout].[png]*/
	var substring = this.src.split("_");
	this.src = substring[0] + "_" + "Mouseout" + "." + photoExtension;
}
/* end my functions */

/* Starter code */

//Create array
var imageSources = new Array();
var arrayCounter = 0;

window.onload = function ()
{
	imageSources = LoadImages();
}

//add slideshow listener
var slideshowNext = document.getElementById("slideshow-next");
var slideshowPrevious = document.getElementById("slideshow-previous");

var image = document.getElementById("slideshow-image");

var homeButton = document.getElementById("home-button");
var aboutButton = document.getElementById("about-button");
var orderButton = document.getElementById("order-button");
var galleryButton = document.getElementById("gallery-button");
var contactButton = document.getElementById("contact-button");

var photoExtension = "png";

addEventSimple(slideshowNext, "click", NextImage);
addEventSimple(slideshowPrevious, "click", BackImage);
addEventSimple(homeButton, "mouseover", ChangeButtonImageMouseOver);
addEventSimple(homeButton, "mouseout", ChangeButtonImageMouseOut);
addEventSimple(aboutButton, "mouseover", ChangeButtonImageMouseOver);
addEventSimple(aboutButton, "mouseout", ChangeButtonImageMouseOut);
addEventSimple(orderButton, "mouseover", ChangeButtonImageMouseOver);
addEventSimple(orderButton, "mouseout", ChangeButtonImageMouseOut);
addEventSimple(galleryButton, "mouseover", ChangeButtonImageMouseOver);
addEventSimple(galleryButton, "mouseout", ChangeButtonImageMouseOut);
addEventSimple(contactButton, "mouseover", ChangeButtonImageMouseOver);
addEventSimple(contactButton, "mouseout", ChangeButtonImageMouseOut);



I hope that is enough info. Thanks for the reply. I am going to read up on jQuery in the mean time.
Was This Post Helpful? 0
  • +
  • -

#4 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4353
  • View blog
  • Posts: 12,160
  • Joined: 18-April 07

Re: Javascript does not work in all pages.

Posted 14 May 2011 - 11:37 AM

Ok, the problem is that your other pages don't have the next and previous buttons. Your script in behavior.js has a section where it tries to reference these elements on the page...

//add slideshow listener
var slideshowNext = document.getElementById("slideshow-next");
var slideshowPrevious = document.getElementById("slideshow-previous");



Then it tries to attach the event handlers to them here...

addEventSimple(slideshowNext, "click", NextImage);
addEventSimple(slideshowPrevious, "click", BackImage);



This triggers the addEventSimple code at the top of that .js file and tries to check if addEventListener is a method of "element". Element being the slideshowNext and slideshowPrevious items you pass to it. Since those elements don't exist on the other pages (only the home page) it is passing null to addEventSimple and then throws an error when you try to check for the existence of addEventListener because element is not set to anything.

How do you fix? Before you go and try to attach events to items you get using document.getElementById() make sure they are not null.

var slideshowNext = document.getElementById("slideshow-next");

if (slideshowNext != null) {
    // go ahead and call addEventSimple and give it slideShowNext
}



Get what I am saying? :)
Was This Post Helpful? 0
  • +
  • -

#5 cRaZi_RiCaN  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 25-May 07

Re: Javascript does not work in all pages.

Posted 14 May 2011 - 11:47 AM

Ok, so once it encounters an error it stops executing the JS completely. I will set up if's to make sure every DOM object exists before calling it. Do I have to do the same thing for variables that may or may not be present in all pages?

I am guessing its a better practice to have separate JS files for each page, right?
Was This Post Helpful? 0
  • +
  • -

#6 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4353
  • View blog
  • Posts: 12,160
  • Joined: 18-April 07

Re: Javascript does not work in all pages.

Posted 14 May 2011 - 11:57 AM

No you do want to keep all the javascript in a single file if it makes sense for page operations. You don't want to be repeating code for each page. You just want to make sure you check the existence of objects and variables you use before you attempt to use them. This is especially important for any DOM objects.

As for variables, they are always thrown away after you leave the page so you have to keep defining them either through the use of your script or on the page itself. They are never carried from page to page.

:)
Was This Post Helpful? 0
  • +
  • -

#7 cRaZi_RiCaN  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 25-May 07

Re: Javascript does not work in all pages.

Posted 14 May 2011 - 12:03 PM

How about if in page 1 the var car is used and in page 2 it isnt (the element does not exist on page 2), will it screw up the JS execution?
Was This Post Helpful? 0
  • +
  • -

#8 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4353
  • View blog
  • Posts: 12,160
  • Joined: 18-April 07

Re: Javascript does not work in all pages.

Posted 14 May 2011 - 10:51 PM

If you define a variable "car" in your js file which you link to both pages, it will be available in both pages and you can use it as normal. You can't set it one page and expect the second page to access its value (each page is running a fresh copy of the variable). The only thing you have to watch is trying to grab elements on the page that are not on every page. You can't grab for a DOM element like "next" if on page 1 you have "next" but not on page 2. It will work on page 1 but not on page 2.

:)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1