Jquery: how to register an event on all pages? - javascript

I want to run the following jquery code on every page in my website.
$(document).ready(function(){
$("#more").click(function(){
$("#morediv").slideToggle("slow");
return false;
});
});
In all my pages I have the more and morediv elements defined, for every page I have different js file and adding this code in every file will not be a good solution (I suppose).
I have created a global.js to include this code, but in other pages also I have the $(document).ready(function(){} function defined and may be that's why its conflicting and not running properly.

You can have multiple $(document).ready(function(){}) elements on your page, so that it's the problem. I suggest using Firefox/Firebug and examining any console errors you find to discover the problem. Perhaps your global.js file is being loaded before jQuery itself? Otherwise, you'll need to dig into it with Firebug's debugger.

Are you actually doing some server-side programming or you are talking about plain HTML pages. I would advise that you have templates (this is specific to your development environment and tools of choice) and include the JS in those templates. Then the actual pages will all use the template and have the JS available. The question you are asking has in fact nothing to do with Javascript or JQuery, but the way you organize your site... unless I'm missing something.

having $(document).ready() event handler in global.js and the page it is included in does not poses any problem I'm using it and it works really fine.

Just a guess, but are you referencing the location of the global.js file correctly?
To be sure, write something like the following into your global script:
$(document).ready(function(){
alert("document ready");
$("#more").click(function(){
$("#morediv").slideToggle("slow");
return false;
});
});
If you don't get the alert the script is not pathed correctly, or is not placed after the jquery include (or the jquery include is not pathed properly).

Related

How to add jquery and javascript to the same file?

I don't know if this is possible. This is how my js file will look like:
$(document).ready(function(){
$("li#dropdown").on('click', function(e) {
$('#toggleList').slideToggle();
e.preventDefault();
});
});
//javascript code...
Will this be possible? or is it better to have my javascript code in another file
That depends entirely on what you want to do.
If your javascript has code, that will be used inside of your $().ready event then you should put it before the $().ready.
The rule is code with functions to do specific stuff, you can call it "your" library, and you should put that code in a separated file.
Code that deals with event handling of your page controls, you should put on a file with [the name of the page].js, but this is just a way for you to organize stuff.
Because javascript is so flexible if you want you can put all in the same file, and it will work generally.
Jquery is an library made out of javascript code.
So actually you are writing javascript in javascript.
So you can combine it, what is already combined :P
haha
You can script inside jquery with javascript goodluck!
That is going to work well and accurate. There is no issue with the code, to be written in jQuery or JavaScript.
jQuery is just a library written in JavaScript. jQuery just shorten downs the code for you. There is no other major difference.
$(document).ready(function(){
$("li#dropdown").on('click', function(e) {
$('#toggleList').slideToggle();
e.preventDefault();
});
});
Would work in every browser, when you have included your jQuery plugin in your web app. Otherwise browser won't be able to recognize $ character and you'll get error. That's the thing you need to worry about only.
.slideToggle() is just a method; function, or jQuery. e is handler for event, and the preventDefault is also a part of JavaScript. So you can see, that jQuery and JavaScript are alike. There is no major difference.
JavaScript is executed by every browser. So it would be executed as it is by every browser.

Including javascript files

I'm finishing my project right now and see that I've got a lot of javascript code on each page. It's not included as a ".js" file, but rather coded in the page itself. I figured it's a bad idea, so now I'm trying to put them all in one .js file and include it in each page.
The only problem I'm facing now is this: Some functions are only called on certain pages and are depending on the inclusion of jquery plugins. Not all pages needs the plugin however.
Example:
On the home page I need to chain the Country dropbox with the City dropbox, thus I need the jchained.js plugin for jquery. The code I need to use is:
$(function(){
$("#city").chained("#country");
});
When I add this function to the .js file, and I open a page where I don't need to chain the dropboxes I get logically an error:
TypeError: $("#city").chained is not a function
So if I understand this correctly, in order to use a .js file with all my different functions for different plugins, I need to include all the plugins to all the pages?
Thanks for your ideas & help.
Personally, I don't think you should worry about including alot of .js files, that's part of web development. Another option, albeit slightly more tedious, is you can make a check for the function to exist (if the plugin .js has been included) and then call it if it does:
if(typeof yourFunctionName == 'function') {
yourFunctionName();
}
It completely depends on how the code is structured or how complex the current code is.
An immediate solution will be,
Give an id to each page (may be on body tag).
Put all the code in a single external JavaScript file.
Execute the code meant for that particular page only if it has required id on that body element.
Something like :
if ( $('body').attr('id') == "home" ) {
/* Add home page JS here */
}
You can try this.
Correct me if I am wrong.

SignalR $.connection is undefined

I admit it, I don't know what I'm doing.
I'm attempting to learn how to use SignalR and I'm following various samples online almost verbatim and I can't get pasted $.connection being undefined. I'm working in MVC 4.0 and trying to use either nuget-downloaded signalR js files or those from sample projects. These are my script references.
#Scripts.Render("~/Scripts/jquery-1.7.2.min.js")
#Scripts.Render("~/Scripts/knockout-2.0.0.js")
#Scripts.Render("~/Scripts/jquery.signalR.js")
#Scripts.Render("~/signalr/hubs")
The scripts seem to load - I've even put alerts at the start of them which fire, but $.connection is always undefined.
In a bizarre turn of events, I have a different project where I'm trying to use a different jQuery library and it uses $. and that object is ALSO always undefined.
I'm just looking for any possible explanation of what I might be doing wrong. Thanks very much in advance.
I got the same problem today.
Your answer pointed me in the right direction, because I had the EXACT same setup for script loading.
I had all my script tags on the top of the page (head) in the following order.
JQuery
SignalR
/signalr/hubs
my-script.js
And of course, the #Layout.cshtml was so thoughtful to add #Scripts.Render("~/bundles/jquery") at the bottom of the <body> tag.
Here's what's happening.
In this configuration, when the page loads, it loads up all the scripts in the head tag, in the order they're specified.
so it loads JQuery, then SignalR, which setup $.connection then the auto-generated hubs script which sets up the $.connection.hubName,then the site's custom script.
At this point your custom code runs. BUT your code at some point, waits for the body.onload or document.onReady before accessing the $.connection
By the time this event fires, the script bundle which the Layout template added for you at the end of body tag also downloads and executes. This bundle has the jquery library again.... which resets everything SignalR setup on $ and now your $.connection is not defined anymore.
How to Solve It
Easy fix, make sure you don't load JQuery twice, once before SignalR and once after SignalR. I moved all my scripts to load after the bundle and it fixed the issue. Best practice here is to use the 'scripts' section provided by the template.
#section scripts{
#*/* load your scripts here. You can exclude jQuery,
coz it's already in the template */ *#
}
So this is not a SignalR error at all...
That's 2 hours of my life... I'll never get back ...
Hope This Helps.
I solved the problem. I know what I did but I don't know why it worked for sure.
I was referencing the main jquery library (version 1.7.2) at the top of the _Layout.cshtml view, but was not referencing any other jquery scripts. I noticed that by default in the layout view it was loading
#Scripts.Render("~/bundles/jquery")
at the bottom of the view and that a scripts section was located below that.
#RenderSection("scripts", required:false)
I further changed my script references as shown and put my script references shown in the question above inside a
#section scripts
{
#Scripts.Render("~/Scripts/jquery.signalR-0.5.1.js")
#Scripts.Render("~/Scripts/jquery.color.js")
#Scripts.Render("~/signalr/hubs")
#Scripts.Render("~/Scripts/blasht.signalr.js")
}
wrapper on my view so that they would be included after the bundles were loaded. I assume that I was not loading all the necessary jquery because now it works.
Now if I can figure out how this applies to my other projects.
The reason this works is because of the order in which the javascript files are loaded. If you try and load jquery.signalR-0.5.1.js before loading jquery, then you will face the $.connection undefined because for this to register the jquery should be loaded first. In the _Layout.cshtml template the scripts load in the order
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
So inside any of your views you can load signalr under the script section and this should work fine.
I have had same issue.
for me I have included jquery 2 times in page and later in layout.
Removed one of them fixed the issue.
Hope it helps
This happened to me because I dynamically loaded the ~/signalr/hubs script before loading the jquery.signalR-1.1.4.js script.
When dynamically loading, no error was present, however if I took the output of ~/signalr/hubs and pasted it into my chrome dev tools, I received an error message VM1047:18 Uncaught Error: SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/hubs.
at <anonymous>:18:15
at <anonymous>:300:2

JavaScript function not found in JSP

I have a few JSP pages, that include some JavaScript(jquery, jquery mobile and some javascript functions that I wrote).
When loading the pages and try to run my functions, I get in Firebug an error, that the function was not found. I have looked into the page source, and the function is there.
All the other jquery mobile functions work.
The only way to make my script work is to make a forced refresh(ctrl+f5).
Why is this happening? How can I fix it?
EDIT
It seems that a simple refresh would also work.
Here is the source code of the page:
http://pastebin.com/6sJnfPDQ
I have retagged your question to remove "Java" and "JSP", as this is irrelevant (server vs browser).
Once your JSP is rendered in the browser, please do look in the page source and see what happened to your tags.
make sure all of your js files are being loaded properly.
also make sure that your js files are being loaded in the proper order.
make sure that, where necessary, you're wrapping your JS in a document ready function of some type
also, I recommend that you add the type attribute to your script tags:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>

External javascript file not working

I have some javascript that's loading just perfectly at the bottom of my site. I wanted to externalize this aforementioned js, so I'm now linking to the code externally, but now the code breaks and is pointing to an error (not within the js file but the jquery file). What changes when the js is externalized? Are variables retrieved in the same way?
Thanks
You probably added the <script> tags in the wrong order.
you can probably use firebug and see whats happening there.
there is net panel which shows whethere that particular js is downloaded propery or not.
after that you can see the errors on the console window of firebug to find what exactly is the error.

Categories