Why function in Javascript file does not load in master page? - javascript

I have a master page that has javascript files added with asp:ScriptReference, but in document.ready ( $(function(){}) ) the functions defined in the Javascript file do not load, and I get this error:
Microsoft JScript runtime error: Object doesn't support property or method 'nanoScroller'.
Whereas the same code runs in other simple projects.

Dear friend if you are using ajaxtoolkite and you are using updatepanel or scriptmanager then jquery make a conflict with it so you can use the following 2 method to make your code work properly the bellow code will solve your problem
$(document).ready(function() {
// bind your jQuery events here initially
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
// re-bind your jQuery events here
});

Related

Is there a way to use jQuery functions if they are not defined in the `$(document),ready` function?

I have several scripts and the $(document).ready is being defined in another script. I tried defining functions in another file that make use of JQuery syntax but they don't work. Is there a way to use jQuery functions if they are not defined in the $(document),ready function?
Here is my first script. it's just a ready block (yes its empty):
$(document).ready(function () {
});
This is my second script:
function editPage() {
$("#mybutton").click(function() {
alert("Clicked");
});
}
editPage();
It does not work.
The second code does not work. They are in different files. The first script is always loaded. I have the jquery library defined. If i place the click code in the first script, it works.
This is ASP.NET MVC 5
If I understand you correct, as long as you reference JS file earlier, you can use it in all other files which is coming later in sequence.
In following scenario, you can use Jquery in "your-test-file.js"
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.min.js"></script>
<script src="/your-test-file.js"></script>

Creating a very simple jQuery plugin, not working

I've never created a jQuery plug-in before. I'm trying it out and keeping it simple for now- here's my plug-in code which is hosted on a CDN in my company:
(function ($) {
$.fn.displayToastrNotifications = function () {
alert('test');
};
})(jQuery);
I'm referencing this JavaScript file inside my page:
<script src="http://server/sites/CDN/Scripts/toastr-notifications.js"></script>
Finally, in the same page, I have:
$(document).ready(function () {
$.displayToastrNotifications();
});
Am I doing this right? The JavaScript file containing my plug-in code is being brought back to the browser per Firebug. I do not get an alert box when I refresh my page. What am I doing wrong?
EDIT
The console reports an error:
TypeError: $.displayToastrNotifications is not a function
$.displayToastrNotifications();
But, it is a function, at least I think it is...
No, that's not right. You're adding the function to $.fn, so that means it's something to be used as a method of jQuery objects:
$(something).displayToastrNotifications();
If you want a "global" function like $.ajax, then you'd set it up as just a property of $, not $.fn.
since it is a plugin it need to be invoked in a jQuery wrapper object like
$('body').displayToastrNotifications();
Demo: Fiddle

asp.net usercontrol won't fire javascript inside updatepanel

I've seen similar issues to this and answers but none seem to fix the issue.
I have a user control inside an update panel. Inside my user control I output javascript.
The javascript will not fire when triggered. If I move the javascript to the parent page outside of the usercontrol/updatepanels then it fires. This doesn't make sense to do this as I can't use this usercontrol on another page without either duplicating code...by either duplicating the entire javascript (different site) or adding references to a .js file in every page it's used on (same site). It's just less portable
I merely want to output the javascript with the control (inside the update panel).
The updatepanel is mentioned for accuracy of what I'm doing. It doesn't work even if I place the usercontrol outside of updatepanels.
Keeping it simple (This does not work for me):
USERCONTROL:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="_location.ascx.cs" Inherits="_location" %>
<script type="text/javascript">
function test() {
alert('Hello World!');
}
</script>
<a href="javascript:void(0);" onclick="javascript:test();">
Find For Me
</a>
PARENT:
<uc1:_location runat="server" ID="_location" />
Debugging in chrome tells me "Uncaught ReferenceError: test is not defined"
If I add the javascript directly to the onclick as below, it works:
onclick="alert('Hello World!');"
And as stated above, moving the function to the parent page ALSO works.
It's as if the browser ignores the script output from the user control.
Any ideas?
When you have an UpdatePanel and that UpdatePanel updates it's content, it treats it's content as simple text/html (not code), it does not have any parser available to run the script and make it available for the page.
So this content,
<script type="text/javascript">
function test() { alert('Hello World!'); }
</script>
<a href="javascript:void(0);" onclick="javascript:test();">
Find For Me
</a>
after client side code of update panel runs and updates content of the page, the script part is not parsed - its simple text/html for the page.
This part however runs
Find For Me
because the parse of the onclick attribute is done when you click on it.
There are following workarounds available:
Move your javascript into external file
Move you script outside of the UpdatePanel
Register the script in the code behind with RegisterClientScriptBlock or alternative functions.
In Addition to the solution that Adam Wood posted, I should say that you must use ScriptManager to register the script when using update panel, at least in .net 4.0 because otherwise it won´t work.
So you can put on the PageLoad event of the usercontrol:
string script = #" alert('this is a test');
alert('it worked')";
ScriptManager.RegisterStartupScript(Page,Page.GetType(),"scriptMelhoria",script,true);
Thanks to Aristos for sending me down the right path... Though his solution works, it did not answer the question of outputting the javascript from inside the usercontrol but instead suggested moving it outside. This was not the desired outcome, as stated, as it's not kept inside the control for easier portability.
Here is my solution that accomplishes this:
CS file:
String script = "<script type=\"text/javascript\">";
script += "function test() {";
script += "alert('Hello World!');";
script += "</script>";
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "locationScript", script);
One might use a stringbuilder if script is longer, but eitherway works.
This keeps the code entirely inside the usercontrol and it works from the onclick event of the a tag.
Try this;
You can find your script elements after udpdate panel callback and evaluate them.
Add a special attribute to your inline script tag to select elements after callback request.
<script type="text/javascript" data-tag='myscript'>
function test() {
alert('Hello World!');
}
</script>
And add this script to your update panel container aspx file.
<script>
if (Sys !== undefined) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(endPostbackRequest);
}
function endPostbackRequest(sender, args) {
$("script[data-tag='myscript']:not([data-run])").each(
function () {
eval.apply(window, [$(this).text()]);
$(this).attr('data-run', '1');
});
}
</script>
Preferred way of dealing with javscript code that is bound to DOM elements within UpdatePanel is to subscribe to endRequest event of PageRequestManager and execute your code here. For instance you want to set click event handlers here.
// that is standard way for asp.net to execute JS on page load
// pretty much the same as $(function(){ ...}) with jquery
function pageLoad() {
// find PRM instance and subscribe to endRequest
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
}
function endRequest() {
// set all handlers to DOM elements that are within UpdatePanel
$('<%= myButton.ClientID %>').on('click', test)
}
function test(e) {
alert('Hi')
}
Alternative solution will be to use event delegation like so:
function pageLoad() {
// delegate click event on .myButton inside .container
// to the .container DOM element
$('.container').on('click', '.myButton', test)
}
And have div with a class named container around your update panel. In this case your div.container is never removed from DOM so all event handlers on it will hold after partial postbacks.
Same code without jquery and using only asp.net ajax will look like this:
function pageLoad() {
Sys.UI.DomEvent.addHandler($("myContainer"), "click", delegatedTest);
}
function delegatedTest(e) {
// since asp.net ajax does not support event delegation
// you need to check target of the event to be the right button
if (e.target.id == "myButton") test(e)
}
function test(e) {
alert("HI")
}

Binding jquery-multifile to a dynamically loaded form

I am using the jquery multifile plugin found here:
http://www.fyneworks.com/jquery/multiple-file-upload/
I've used it in the past and had no problems, but now I am trying to use it in a dynamically loaded form and it's causing a strange issue.
I am binding the function correctly when loading the form as per this article, so please understand this is a DIFFERENT, albeit related, problem to the one posted here:
Cannot bind input event to jQuery multifile from dynamically loaded form
$('#reportWindow').on('click', '#continueReport', function () {
var data = $('.reportForm').serializeObject();
$('<div/>').load('/Forms/report.aspx', data, function () {
doReportForm(this);
});
});
An ASPX file is being loaded into a div using jquery load as per the above, the doReportForm function is to call in various binding methods to that dynamically generated HTML as per:
function doReportForm(ele) {
$(ele).makeModal('', 800);
FB.XFBML.parse();
checkLogin();
clearNetIds($('#reportForm2'));
$("#datePicker").datepicker({
changeMonth: true,
changeYear: true
});
$('[class*="toolTip"]').setupTip();
$(".multi").MultiFile(); // input[type=file]
$('#right').on('click', '#savePost', function () {
var data = $('.reportForm2').serializeObject();
});
};
The first line there, $(ele).makeModal('', 800); is simply a jQuery extension I made to create modal windows, so it as it THIS point where the element is added to the DOM, then a few lines down I bind the MultiFile plugin thus $(".multi").MultiFile();
The first time this is done, it works fine. But, when a user closes the modal window and then tries to load the form again I get an error.
Uncaught TypeError: Cannot call method 'apply' of undefined
(closing the modal window removes it completely from the DOM with jQuery.remove(), so any future windows are written completely from fresh).
After a bit of fiddling, it appears that this is due to jQuery not being able to access the MultiFile script... I think
The MultiFile script is loaded in the head of the parent document, so should be available at all times.

Using jQuery noConflict() with script.aculo.us

I have a site using a "widget" (from http://healcode.com) that includes the script.aculo.us JavaScript library. The problem is that the site I'm building is on WordPress, so there's the classic jQuery vs script.aculo.us conflict.
I know that I need to run jQuery in .noConflict() mode, but I must be getting the syntax wrong. When I assign the $ to jQuery .noConflict as follows, it still shuts down the script.aculo.us functions:
var $ = jQuery.noConflict();
$(document).ready(function () {
//#nav-main dropdown effects
$('#nav-main ul li').hoverIntent(function () {
$(this).find('.dropdown').stop(true,true).slideDown('900'); },
function(){
$(this).find('.dropdown').stop(true,true).slideUp('500');
});
}); // end document.ready
I know that I am assigning the $ to jQuery in .noConflict() mode, and I assume that script.aculo.us (which loads via a widget in the main body, therefore AFTER jQuery) is trying to re-assign the $ back to script.aculo.us.
How can I assign the $ to jQuery in a way that the later-loaded script.aculo.us library won't conflict? I've already tried the following without any success (the following code causes script.aculo.us to work, but jQuery to fail):
jQuery(document).ready(function () {
//#nav-main dropdown effects
jQuery('#nav-main ul li').hoverIntent(function () {
jQuery(this).find('.dropdown').stop(true,true).slideDown('900'); },
function(){
jQuery(this).find('.dropdown').stop(true,true).slideUp('500');
});
}); // end document.ready
EDIT
The debug console output for the above code is:
Uncaught TypeError: Object #<HTMLDocument> has no method 'ready' (anonymous function) so the document.ready fails because it's assigned to jQuery, which is somehow not loading properly...
EDIT 2
Both of the 2 (at the time of this update) answers posted below do nothing to address the issue I'm struggling with. Perhaps they are technically correct, but they do not address my issue.
This worked for me so that I can have jQuery and script.aculo.us/Prototype working well together. Credit goes to codeimpossible for this lifesaver!
Instead of:
jQuery(document).ready(function () {
// Code to run on DOM ready
}); // End document.ready
Try this:
( function($) {
// Code to run on DOM ready
} )( jQuery ); // End document.ready
I found the solution VERY surprising!
First of all, using the $j = jQuery.noConflict(); mode did not work.
Second, calling jQuery.noConflict(); at the head did not work.
The method that did work was this one: http://codeimpossible.com/2010/01/13/solving-document-ready-is-not-a-function-and-other-problems/
Oddly, the Coda Slider 2.0 plugin does not automatically do noConflict so it turned out that IN ADDITION to the problems listed above, I needed to wrap that plugin in .noConflict(); as well. Shout out the the author of the blog post, not sure why other noConflict(); calling methods didn't work, but I'm glad I found the post.
Assigning jQuery right back to $ doesn't do anything.
Either assign jQuery to a different variable:
var j$ = jQuery.noConflict();
Or don't assign it to anything:
jQuery.noConflict();
Try this:
<script src="url to jquery"></script>
<script type="javascript">jQuery.noConflict();</script>
<script src="url to scriptaculous"></script>

Categories

Resources