$.on is not a function - javascript

I am getting following error when trying to run my website,
Uncaught TypeError: $(...).on is not a function
I am not well aware of javascript, hence i dont know what all this code does :
$(window).on('hashchange', function(){
var url = window.location.hash.replace("#/", "");
if(url != ""){
setHashChange(true);
} else {
iniMenuSlide("home");
}
});
Please guide me on how to resolve this error.

Paste below line in your page's head tag, preferably before any javascript linking or code.
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
The error is coming because you are not linking jQuery file or linking to older version, which is not supporting on function.

The on method was introduced in jQuery 1.7 (which is pretty ancient these days). Since you don't seem to have it, you need to upgrade to a more recent version of jQuery.
The code calls one of two different functions depending on if the URL has changed to one with fragment identifier at the end or not.

Related

How can I modify jQuery to allow $('dialog').showModal() to work?

I am trying to show a modal dialog using a jQuery script. Using the $ approach to get the element and call the function results in an error, but using vanilla JS to get the element and call the function works as expected. How can I make the call work using the $ approach to get the element?
Vanilla JavaScript
Works as expected. No errors on Chrome v67.0.3396.87.
document.getElementById("error").showModal()
<dialog id="error">Error message</dialog>
jQuery (v3.3.1)
Does not work as expected. Returns an error on the same browser.
Uncaught TypeError: $(...).showModal is not a function
$('#error').showModal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<dialog id="error">Error message</dialog>
I realize what's probably happening is dialog.showModal() functionality is still experimental, so jQuery may not have formal support for it yet. However, I expected that any functions or properties not overridden by jQuery would cascade to the vanilla JavaScript functions and properties. That is evidently not the case, so I could use some help to make $('#dialog').showModal() behave functionally like document.getElementById("dialog").showModal().
Edit: I'm trying to use this like any other typical jQuery call within my scripts. For more context, here's how I'm trying to use the calls.
err = $('#error');
err.html('New error message'); //err = $('#error')[0] results in an error here
err.showModal(); //err = $('#error') results in an error here
//err.show() does not create the supporting elements that showModal() does
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<dialog id="error">error</dialog>
Extend jQuery
jQuery.fn.extend({showModal: function() {
return this.each(function() {
if(this.tagName=== "DIALOG"){
this.showModal();
}
});
}});
Use as
$('#error').showModal();
Modifying the showModal() call meets my requirements:
$.fn.showModal = function() {
el = $(this);
if (el.is('dialog')) {
el[0].showModal();
}
return el;
};
err = $('#error');
err.html('New error message');
err.showModal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<dialog id="error">error</dialog>
At some point I'll need to add in browser compatibility checks to cascade to some degraded mode alternative. Also need to add a jQuery version number check in case formal support for the call is added in a future version.

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

Hi I am having a "Uncaught ReferenceError: $ is not defined" while using bellow codes
I am currently getting the following error in my log. I have been looking at the samples in the framework and I just can't seem to find where the error is. It's been over a decade since I have done any HTML or js and what I did back then was very basic stuff. Any help would be appreciated
<script type="text/javascript">
var sQuery = '<?php echo $sQuery; ?>';
$(document).ready(function(){
if($('input[name=sPattern]').val() == sQuery) {
$('input[name=sPattern]').css('color', 'gray');
}
$('input[name=sPattern]').click(function(){
if($('input[name=sPattern]').val() == sQuery) {
$('input[name=sPattern]').val('');
$('input[name=sPattern]').css('color', '');
}
});
$('input[name=sPattern]').blur(function(){
if($('input[name=sPattern]').val() == '') {
$('input[name=sPattern]').val(sQuery);
$('input[name=sPattern]').css('color', 'gray');
}
});
$('input[name=sPattern]').keypress(function(){
$('input[name=sPattern]').css('background','');
})
});
function doSearch() {
if($('input[name=sPattern]').val() == sQuery){
return false;
}
if($('input[name=sPattern]').val().length < 3) {
$('input[name=sPattern]').css('background', '#FFC6C6');
return false;
}
return true;
}
</script>
It seems you don't import jquery. Those $ functions come with this non standard (but very useful) library.
Read the tutorial there : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
It starts with how to import the library.
No need to use jQuery.noConflict and all
Try this instead:
// Replace line no. 87 (guessing from your chrome console) to the following
jQuery(document).ready(function($){
// All your code using $
});
If you still get error at line 87, like Uncaught reference error: jQuery is not defined, then you need to include jQuery file before using it, for which you can check the above answers
Put this code in the <head></head> tags:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
If you are sure jQuery is included try replacing $ with jQuery and try again.
Something like
jQuery(document).ready(function(){..
Still if you are getting error, you haven't included jQuery.
I know this is an old question, and most people have replied with good answers. But for reference and hopefully saving somebody else's time. Check if your function:
$(document).ready(function(){}
is being called after you have loaded the JQuery library
many other people answered your question above. This problen arises when your script don't find the jQuery script and if you are using other framework or cms then maybe there is a conflict between jQuery and other libraries.
In my case i used as following-
`
<script src="js_directory/jquery.1.7.min.js"></script>
<script>
jQuery.noConflict();
jQuery(document).ready(
function($){
//your other code here
});</script>
`
here might be some syntax error. Please forgive me because i'm writing from my cell phone. Thanks
Remember that you must first load jquery script and then the script js
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="example.js"></script>
Html is read sequentially!
$ is a function provided by the jQuery library, it won't be available unless you have loaded the jQuery library.
You need to add jQuery (typically with a <script> element which can point at a local copy of the library or one hosted on a CDN). Make sure you are using a current and supported version: Many answers on this question recommend using 1.x or 2.x versions of jQuery which are no longer supported and have known security issues.
<script src="/path/to/jquery.js"></script>
Make sure you load jQuery before you run any script which depends on it.
The jQuery homepage will have a link to download the current version of the library (at the time of writing it is 3.5.1 but that may change by the time you read this).
Further down the page you will find a section on using jQuery with a CDN which links to a number of places that will host the library for you.
(NB: Some other libraries provide a $ function, and browsers have native $ variables which are only available in the Developer Tools Console, but this question isn't about those).

use of globalstorage is deprecated. please use localstorage instead

I got this message when doing some javascript programming, and after some google searches, I have no idea what it means, or how i cause this error. I'm including the code below, can someone explain it to me or point me to a resource on how to fix it or what is happening at all? The weird thing is that I have other code just like this part in my program, and it never gives me errors about them, so i'm really confused. Also, I only get this error to display with firebug running, else wise it just doesn't work and no error message is displayed. I also tried it in Chrome, and had the same issues, no error message but the code doesn't work.
foundTextFn = function(){
console.log('fire');
if (foundTextArrayPosition != foundTextArray.length){
writeText(foundTextArray[foundTextArrayPosition],"happy");
foundTextArrayPosition += 1;
}
foundTextFnTimer=setTimeout("foundTextFn()",4000);
}
Here is another of my methods, it is basically the same thing, but it works fine. And if it matters, all of these variables are global variables declared at the start of my file as var foundTextArrayPosition = 0; for example.
awayFn = function(){
if (awayArrayPosition != awayArray.length){
if (changeAwayState){
changeAwayState = false;
writeText(awayArray[awayArrayPosition],"normal");
awayArrayPosition ++;
temp = pickRandomSpot();
randomX = temp[0];
randomY = temp[1];
}
else{
changeAwayState = true;
}
awayTimer=setTimeout("awayFn()",10000);
}
else{
abandoned = true;
whyGoneArrayPosition = 0;
whyGoneFn();
}
}
This is a deprecation error in Firefox 9. globalstorage was a way to store data in Firefox, but HTML5 introduced localstorage, which is now the preferred way (using window.localStorage).
https://developer.mozilla.org/en/DOM/Storage has more information.
I got the same error message and found a solution and perhaps the underlying cause of conflict, I was using the jQuery validate function in the jzaefferer.github.com/jquery-validation/jquery.validate.js library along with jQuery 1.7.1
The problem:
I used $(document).ready with two different contexts. One with the noConflict wrapper and one without. By keeping both the same, the error message went away. Hooray!
The wrapper:
jQuery.noConflict();
jQuery(function($) {
$(function() {
$(document).ready(function() { ...}
});
});
See also this post on my blog.
Probably not related to the issue above but I will put it here for the search engines.
I got the same error message while doing some simple jQuery:
Use of globalStorage is deprecated. Please use localStorage instead.
[Break On This Error]
$(document).ready(function() {
It was however due to forgetting to actually include the link href to the jQuery.js file...!

Running javascript code called by AJAX

My site uses pushState to load pages. I have one issue, I want to use javascript on one of the pages but can't because it loads everything with AJAX. So what do I do? I've been told something about "parseScript" but I can't find enough information on it.
--Example--
I load using AJAX
On my page I have this script:
<script type="text/javascript">
function go(){
alert('1');
}
</script>
GO!!!
Nothing happens.
--Edit--
If I open up Google Chrome's debugger:
"Uncaught ReferenceError: go is not defined"
And the <script> tag is no where to be found
Browsers don't seem to parse <script> element content that's added to the document via targetElement.innerHTML. That's probably what you're running into.
The best solution is to use a well-tested framework like jQuery for solving problems like this. They've already figured out how to safely and correctly inject scripts into the DOM. There's no sense re-inventing the wheel unless you absolutely can't spare the bandwidth for the library.
One way you might fix this is by separating the JavaScript from the HTML in the Ajax response, either by issuing two requests (probably slower) or by structuring your JavaScript and HTML within a JSON object (probably harder to maintain).
Here's an example:
<script>
function load_content(){
var req = new XMLHttpRequest();
req.open("GET", "ajax.json", true);
req.onreadystatechange = function (e){
if (req.readyState === 4){
if (req.status === 200){
// these three lines inject your JavaScript and
// HTML content into the DOM
var json = JSON.parse(req.responseText);
document.getElementById("target").innerHTML = json.html;
eval(json.js);
} else {
console.log("Error", req.statusText);
}
}
};
req.send(null);
}
</script>
Load more stuff
<div id="target"></div>
The document ajax.json on the server looks like this:
{
"js": "window.bar = function (){ console.log(\"bar\"); return false; }",
"html": "<p>Log a message</p>"
}
If you choose this route, you must either:
namespace your functions: MyApp.foo = function (){ ... };, or
explicitly add your functions to the global namespace: window.foo = function (){ ... };.
This is because eval executes in the current scope, so your function definitions inherit that scope and won't be globally available. In my example, I chose the latter option since it's just a trivial example, but you should be aware of why this is necessary.
Please make sure to read When is JavaScript's eval() not evil? if you decide to implement this yourself.
I think it would be helpful to have a little more detail as to how the Ajax call is made and the content is loaded. That said, a few things of note:
the syntax for javascript:void() is invalid. It should be javascript:void(0). For that matter, using javascript:void() on the href of an anchor tag is generally bad practice. Some browsers do not support it. If you must use an tag, set the href to # and add "return false;" to the click event.
you should use a button tag instead of the a tag in this case anyway.
given what you have provided, it should work (aside from the syntax error with void())
If I were to do this I would use jquery's load call.
That takes care of putting an ajax call ,and parsing tags for script/no-script elements.
IF you dont wanna use jquery, I would suggest you go online and find what the jquery load method does and implement the same as an event handler for your ajax call.

Javascript error

I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!
<SCRIPT language=JavaScript>
<!--
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("\/_layouts\/images\/icon1.gif");
newImage("\/_layouts\/images\/icon2.gif");
// -->
</SCRIPT>
The error I am getting is when clicking on a drop down context menu on a page, for this line:
newImage("\/_layouts\/images\/icon1.gif");
The object doesn't accept this property or method
Code: 0
I really don't see what could happen... Any tips on what may be happening here?
Have you tried loading your scripts into a JS debugger such as Aptana or Firefox plugin like Firebug?
Why are you escaping the forward slashes. That's not necessary. The two lines should be:
newImage("/_layouts/images/icon1.gif");
newImage("/_layouts/images/icon2.gif");
It is hard to answer your question with the limited information provided:
You are not showing the complete script
You never said what the exact error message is, or even what browser is giving the error.
Which line number is the error supposedly coming from?
I'd recommend using Firebug in firefox for debugging javascript if you aren't already. IE tends to give bogus line numbers.
And as others have already said, the language attribute for script tags is deprecated.
Write proper xml with the " around attributes.
<script type="text/javascript">
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("/_layouts/images/icon1.gif");
newImage("/_layouts/images/icon2.gif");
</script>
should your script block not be:
<script type="text/javascript">
?
For starters, start your script block with
<script type="text/javascript">
Not
<script language=JavaScript>
That's probably not the root of your problem, but since we can't see your script, that's about all we can offer.
You probably need to enlist the help of a Javascript debugger. I've never figured out how to make the various debuggers for IE work, so I can't help you if you're using IE.
If you're using Firefox or you CAN use Firefox, make sure you have a Tools / Javascript Debugger command. (If you don't, reinstall it and be sure to enable that option.) Next, open up the debugger, rerun the problem page, and see what comes up.
How are you calling changeImages? It looks as though you are not saving a reference to the images returned by newImage. You probably want to save the results of newImage and pass that to the changeImages routine. Then changeImages should look like this:
function changeImages(a, b) {
a.src = b.src;
}
You also may want to ensure that the images have finished loading before calling changeImages.
You've posted the routine that throws the error, without posting the error or showing us how you are calling it. If none of the answers posted fix your problem then please post some detail about how you are calling the method, which specific line the error is on, and what the error message is.
You firebug to debug.
http://www.mozilla.com/en-US/products/download.html?product=firefox-3.0.10&os=win&lang=en-US
https://addons.mozilla.org/en-US/firefox/addon/1843
JSLint is also a nice resource.
http://www.jslint.com/
Using CDATA instead of the <!-- // -->
http://www.w3schools.com/XML/xml_cdata.asp
<script type="text/javascript">
<![CDATA[
]]>
</script>

Categories