Problems Getting jQuery to Work in External js File - javascript

I have just started messing with jQuery and have had luck getting it to work within actual aspx and html files, but I'm now trying to get it working in an external js file.
In my html file in the head I have:
<!--Declare jQuery files-->
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1-vsdoc.js"></script>
<!--Declare external java files-->
<script type="text/javascript" src="javascript/SiteFunction.js"></script>
I have tried adding this to avoid multiple document ready instances, it hasn't effected anything either way, having in or not:
<script type="text/javascript">
$(document).ready(function() { });
</script>
In my external file I have (it is in an if statement and my function just literally skips over all the jQuery .append and .animate stuff as if it were not even there):
$(document).ready(function() {
$('<p>Test</p>').append("#" + newPage);
});
jQuery(function($) {
alert(newPage);
$('<p>Test</p>').appendTo(newPage);
$(newPage).animate({ left: '0px' }, 2000, function() {
// Animation complete.
alert("animated newPage");
});
$(currentPage).animate({ right: '0px' }, 2000, function() {
// Animation complete.
});
});
The first jQuery append is just a simple test to see if I could do something simple. This is all contained in an if statement. I am not receiving any errors and the code is preceding through the first jQuery ready, going into the jQuery function, my alert(newPage) is working, but my alert("animated newPage") is not so I know that I am not even entering into any of the jQuery functions.
If my terminology is incorrect, please forgive me, again I have just started working with Query over the past 3-4 days.
My variables, newPage and currentPage are the id's of divs contained in the main html page. I am accessing and manipulating them fine with javascript in the same external js file.
I tried with the first jQuery .append to see if I needed to add the "#" before my div id to reference as a string.
I've tried with the rest wrapping them in the jQuery(function($) {});. Leaving them as just stand alone, which worked directly from my html file.
Example of working code from html file. Same setup in the head of the file
$(myContent).animate({
width: '0px'
}, mySpeed, function() {
// Animation complete.
});
$('#contentH4').animate({
width: myLeft
}, mySpeed, function() {
// Animation complete.
});
So, I'm at a complete loss!

First, you should only include jQuery once. Those files you're linking to all have the same JS code (except one is minified and the other has additional comments).
This is all you need:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js"></script>
Also, it would help to see where you're defining newPage and currentPage. If you could link to a demo page that would be ideal.
Also, this does nothing:
<script type="text/javascript">
$(document).ready(function() { });
</script>
And if newPage is simply an ID, then this:
$('<p>Test</p>').appendTo(newPage);
Should be this:
$('<p>Test</p>').appendTo('#' + newPage);

When linking external javascript/jquery files, the type="" does not have to be declared.
Also have them load at the bottom of all body content for better load times.

I use ASP.NET with nested MasterPages and this got to be a real issue for me. I was getting document.ready's lost all the time. I figured I needed a better way and what I came up with was creating an array to hold all of my functions that I wanted to call, and in one document.ready, loop through that array, calling each function in the order in which it was added. If you use many external files that are included at different points for different reasons, this will allow you to do that without any hassle:
<!-- your external javascript file -->
<script type="text/javascript">
// create array to hold a list functions to run once
var oneTimeFunctions = new Array;
// create variable to store first function
var test1 = function() { $('<p>Test</p>').append("#" + newPage); };
// add first function to the end of the array
oneTimeFunctions[oneTimeFunctions.length] = test1;
// create variable to store second function
var test2 = function() {
alert(newPage);
$('<p>Test</p>').appendTo(newPage);
$(newPage).animate({ left: '0px' }, 2000, function() {
// Animation complete.
alert("animated newPage");
});
$(currentPage).animate({ right: '0px' }, 2000, function() {
// Animation complete.
});
};
// add second function to the end of the array
oneTimeFunctions[oneTimeFunctions.length] = test2;
// call document.ready only once
$(function(){
// call each function that was added to the oneTimeFunctions array
$.each(oneTimeFunctions, function(index, func) { func(); });
});
</script>
Now, like I said, you can split this up into multiple external files. This just shows it how it would be processed in order. You just need to create the array first, then create your functions and add them to the array in your various external files, and lastly, run the document.ready portion that loops through calling each function.

Related

JavaScript How to pass a parameter to a function

I am having trouble passing a parameter to a function.
Here is my code (edited to show flow and positioning in the html doc):
<!-- this src file precedes -->
// this resides in a js src file on its own and as is
function mySpecialFunction(thisIndex) {
alert(thisIndex); // shows as blank
}
<!-- this src file follows -->
$(document).ready(function() {
$(window).load(function() {
$(document).on('change', '.jq__pAC', function(event) {
var i = 1;
// some JavaScript code
mySpecialFunction(i);
// some more JavaScript code
}); // end jq__pAC
}); // end .load()
}); // end .ready()
my alert() event displays blank.
The 2 blocks of js code are in separate src files. Does that have anything to do with it?
If you say the functions are in different files, probably the order of the files in the problem.
Make sure that the calling method (mySpecialFunction(i);) comes after the declaration (function mySpecialFunction(thisIndex)).
EDIT:
In your edit you have $(document).ready and $(window).load. Remove the last one and it will work.
See jsfiddle.

How do I utilize a predefined method from one js file in my own js file?

I am a web design student and fairly new to jQuery/Javascript so I know this is fairly basic, but everything I have tried has not worked. I am using unslider (unslider.com) on my main page and I am trying to pause the slider on a click event. The documentation on unslider.com shows that you can stop and start the slider based on the following code:
var slidey = $('.banner').unslider(),
data = slidey.data('unslider');
// Pause Unslider
data.stop();
The problem I am having is that I am not sure how to access or utilize these predefined methods in my own js file. Here is the code I am trying, but it is not pausing the slider:
$(document).ready(function() {
$('.button').click(function() {
var slidey = $('.banner').unslider(),
data = slidey.data('unslider');
data.stop();
});
});
Any help with this would be greatly appreciated! Thanks
After the slider is stopped, I am trying to run the following functions:
$details_link = $('.active').data('url');
$('#inner_wrap').load($details_link, function() {
$('.banner').slideToggle( "400", function() {
$('body').toggleClass('no_scroll');
$('#slider_btn').toggleClass('slider_btn_down slider_btn_up');
});
});
Here's a working fiddle.
Make sure that your JS is like so:
$(document).ready(function () {
unslider = $('.banner').unslider();
$('button.stop').on("click", unslider.data("unslider").stop);
});
Then in your HTML make sure that your button is like so:
<button class="stop">Stop the slider</button>
And you're all set.
In terms of utilizing methods from other JS files, just make sure that the location of the script tag for the library you want to use is before your own JavaScript so that the library loads before you can call one of its methods. Something like this, where application.js is your custom JavaScript:
<script src="jquery.js"></script>
<script src="unslider.js"></script>
<script src="application.js"></script>
As long as you have both javascript files linked within the same page, and the file that has the function you are calling is linked first, you will be able to call functions from other files, as described in this post:
Can we call the function written in one JavaScript in another JS file?

Properly loading scripts and dependencies in correct order using head.js?

I am not sure if I am utilizing head.js correctly. In the header of my html document I call the head.js file via:
<script src="/scripts/head.min.js" type="text/javascript"></script>
Then right before the closing < / body > tag in the html page, I call the following file:
<script src="/scripts/load.js" type="text/javascript"></script>
In the load.js file I have the following code:
head.js(
{livechat: "/scripts/livechat.js"},
{jquery: "http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"},
{jquerytools: "http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"},
{slider: "/scripts/jquery.nivo.slider.pack.js"},
{prettyphoto: "/scripts/jquery.prettyPhoto.js"},
{sliderfunctions: "/scripts/slidercode.js"},
{functions: "/scripts/functions.js"}
);
Does the above code cause the javascript files to execute in the same exact order they are listed or do they sometimes execute out of order?
I ask because the slider initially only functioned if I utilized the following code within load.js:
head.ready("slider", function() {
$('#slider').nivoSlider({
effect:'sliceDown',
controlNav: false
});
});
I was able to get around this by moving the above code to an external file called slidercode.js which contained the following code:
$(window).load(function() {
$('#slider').nivoSlider({
effect:'sliceDown',
controlNav: false
});
});
But I am not sure if I am going about this the correct and most efficient way as this is my first time using head.js. Basically from the javascript files in loader.js I need to make sure:
jquery loads first.
Once jquery has fully loaded then jquerytools loads
After jquery is fully loaded, it should load slider first and then prettyphoto.
Then sliderfunctions should load as it is dependent on slider,
Lastly, functions should load as it is dependent on jquery and jquerytools.
You should call the scripts like this: (remove the http as well, it's not needed. Also Jquery always loads first of any scripts. in this case headJS has priority then jquery then all your scripts)
<script src="/scripts/head.min.js" type="text/javascript"></script>
// this loads asyncrounously & in parallel
head.load("//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js", "//cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js", "/scripts/jquery.nivo.slider.pack.js", "/scripts/jquery.prettyPhoto.js", "/scripts/slidercode.js", "/scripts/functions.js");
Then right before the closing < / body > tag in the html page, I call the following file:
<script>
head.ready(function () {
// some callback stuff
$('#slider').nivoSlider({
effect:'sliceDown',
controlNav: false
});
});
<script>
Does the above code cause the javascript files to execute in the same
exact order they are listed or do they sometimes execute out of order?
Yea, they load asyn, but execute in order.
I think head.ready("slider", function() {} );should also work even if you place it outside of load.js. Try adding it after load.js script block.

"$" is undefined; jquery clearly linked to in <head>; no conflicting scripts or libraries

-=- THIS CODE FUNCTIONS. I AM LEFT TO ASSUME THERE WAS A PROBLEM WITH THE CACHE AS NOTHING HAS BEEN ALTERED BETWEEN NON-FUNCTION/FUNCTION. THANK YOU ALL FOR YOUR HELP (especially Niko who got the ball rolling and helped me form a richer understanding of jquery syntax) -=-
I've written this script by hand, and finally decided to update it to jquery in a bid to get used to that, and streamline the code. This is supposed to render a simple menu (which it did before).
Both .js files are in the same directory as the .html file. This is being tested on my pc, not on a server.
A previous version of this code worked perfectly just linking to taskMaster.js. At that point my code didn't use "$" tagged calls.
Firebug is displaying an error of "ReferenceError: $ is not defined" when it tries to call $(document).ready(function () {
the "net" tab doesn't display either .js files as being loaded; the net tab is completely empty and shows no activity - I believe this is because I'm testing this off my PC; the net panel is empty when I load the functioning code
I've reinstalled a fresh version of jquery on the offchance there was something wrong, to no avail
Broken code "taskMaster.js":
$(document).ready(function () {
//main menu
function Main()
{
var mainList = ["New List","Show Lists","Delete Lists"];
//var onClick = [New,Lists,Delete];
var mainMenu = new Menu("Main Menu","menuMain",mainList/*,null*/);
mainMenu.contentMenu();
}
$(Main);
//menu class
function Menu(name,divClass,content/*,onclick*/)
{
$("#interface").html(null);
//title
formatDiv("interface",name,divClass,name/*,null*/);
//return
if(name != "Main Menu")
{
formatDiv(name,null,"return","^ Main Menu","Main()");
}
//display options
this.contentMenu = function()
{
for(i=0; i<content.length; i++)
{
formatDiv("interface",content+i,"menuContent",content[i]/*,onclick[i]*/);
}
}
}
//format divs
function formatDiv(target,divId,divClass,content/*,onclick*/)
{
$("#"+target).append("<div id=\'" + divId + "\' class=\'" + divClass + "\'>" + content +"</div>");
/*$("#"+divId).click(function()
{
onclick;
});*/
}
});
I commented out unused lines, but it's showing "$" as undefined
Here is the HTML:
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="taskMaster.js"></script>
<link rel="stylesheet" type="text/css" href="taskMaster.css" />
</head>
<body>
<div id="interface">
</div>
</body>
</html>
As far as I can tell there is nothing wrong with this html - the same format worked perfectly fine before. All that's changed is that I've introduced jquery and changed some commands in taskMaster.js to use "$".
Okay, I'm now posting this as an answer, because it is easier to provide some examples here.
First thing is: Whenever you do an operation that accesses the DOM, such as $("#interface").html(null);, you will first need to make sure that the DOM is ready. This is what the "ready" event is for:
$(document).ready(function() {
/* The code here is executed when the DOM is ready! */
});
So if "Main()" is a function that kicks everything off, you can simply list it to be called when the DOM is ready:
function Main() {
/* ... */
}
$(document).ready(Main);
Most the time it is also safe to encapsulate the entire JavaScript code in a "ready" event handler:
$(document).ready(function() {
function Main() { /* ... */ }
function formatDiv(...) { }
// ...
// All functions are defined, now let's go:
Main();
});
Now the click handlers: jQuery's "click()" function expects a function that is to be called when the corresponding DOM elements gets clicked on. You're currently passing strings like "New()" to it, but you should directly pass the functions. To do so, alter the code in "Main()" this way:
// Old: var onClick = ["New()","Lists()","Delete()"];
var onClick = [New, Lists, Delete]; // New
This adds the actual functions to the array, not just their names.

Javascript scrolling code

Here is a link to some code that i would like to implement.
http://jsfiddle.net/g7gYy/12/
I am having a bit of trouble working out where to place the code and to actually get it too work.
Here is an html file that I have uploaded: http://www.canning.co.nz/Game/testmarquee.html
Can I please have some help with this?
thanks
First you didnt added jquery lib to your page add it.
<script src="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Next put all your code in document ready because before document get ready your code get executed but elements are not ready to do some operations
$(document).ready(function() {
var $text = $('.text-to-scroll', $marquee);
var textWidth = $text.width();
var $marquee = $('#marquee');
var marqueeWidth = $marquee.width();
$marquee.css('height', $text.height());
function animateLoop()
{
//First lets put if out of view to the left
$text.css('left', -textWidth);
//Now it's out of view, change it's display from none to block
$text.css('display', 'block');
//Now we can animate it so that if scrolls across the screen
//http://api.jquery.com/animate/
$text.animate({ 'left' : marqueeWidth }, 10000, 'linear', animateLoop);
}
});
Your javascript file link is not good.
<script language="JavaScript" type="text/javascript" src="marquee.js">
make sure the marquee.js file is in the same folder as your testmarquee.html page.
Later Edit:
Ow, scratch that, i was wrong, Mateusz was in fact right.:D

Categories

Resources