Inserted JavaScript by usercontrol invokes only on first page - javascript

I have used a user control to get data from database and render it as MegaMenu anchors.
In code-behind file I have got data and rendered it by using a literal.
The megamenu.js file (containging myMega.Init method) has been inserted into header element
I have added following script tag into .ascx file.
<script type="text/javascript">
myMega.Init("mer_id", "anchor_id", "click");
</script>
I have several .aspx files which have same master page. The master page registers the User Control and contains following tag exact before .
<uc:MegaMenu id="anchors" runat="server"></uc:MegaMenu>
the problem is the myMega.Init only invokes when I go to firstpage.aspx. I have debugged by hitting f12 and choosing debugg Script. the init file invokes only first time (firstpage) not other pages. thank you for your help.

are mer_id and anchor_id elements' ids and what .Init does?

If you use jquery library you could put your code in ready event
<script type="text/javascript">
$(function() {
myMega.Init("mer_id", "anchor_id", "click");
});
</script>

Related

asp.net Custome Control and javascript

I have master page with custom button control. I have one javascript function in master page. When i try to call this javascript function with in custom control code behind its not invoking. pls check below code.
Javascript code in master page
function loader()
{
//Note: ctl00_loader is master page control.
document.getElementById('ctl00_loader')="X";
}
Mycustom control is
<Shri:ConfirmBtn ID="UsrBtn" runat="server">
Code-behind code is
Protected Sub UsrBtn_ConfirmClick(ByVal sender As Object, ByVal e As
System.EventArgs) Handles UsrBtn.ConfirmClick
ClientScript.RegisterStartupScript(GetType(String), "MyCode1", "<Script
Language=Javascript>loader();</script>")
End sub
code behind line is working fine in page loading time. but when i place it custom control click (UsrBtn_ConfirmClick) inside its not loading. how to solve this one? any idea please.
Use jQuery:
In the header of your html page:
<script src="https://code.jquery.com/jquery-3.3.1.js" type="text/javascript"></script>
Then capture the button click
$("#<%=UsrBtn.ClientID%>").bind("ConfirmClick", function () {
// Do whatever you need here ....
});
To debug code embedded in the page add the keyword debugger; like so:
$("#<%=UsrBtn.ClientID%>").bind("ConfirmClick", function () {
// Do whatever you need here ....
debugger;
});
This will force the IDE to stop on that line then you can use the F10 key to step through the code like you would in the code behind.

How to do some operation after web another page is loaded?

Hello I have some JavaScript code to fill some table of page1 and auto click its submit button, then it jump to another page2.
What I want is to execute some other codes after page2 is fully loaded. I know methods like window.onload and jQuery.ready but i don't know how to set this method to page2. For example if i write window.onload then the window reference to the current page.
Can anyone help?
You could achieve it the following way.
example :
Add unique identification classes to each of the page body.
page 1
<body class='page1'></body>
page 2
<body class='page2'></body>
JavaScript
in your javascript file, use the following to run the code.
if($('body').hasClass('page1')){
//run page 1 code
}else{ // You can add a second if just to check if it's page 2
//run page 2 code
}
Then import the file to both pages at the bottom of the body tag. the script will run as needed.
Update
To get the current browser url just use window.location.href to get the url. The url is a unique page identifier so just update the condition to the following.
if(window.location.href == 'page1-url'){
//run page 1 code
}else{ // You can add a second if just to check if it's page 2
//run page 2 code
}
I would prefer using the window.location.pathname since it would just return the page path without the host, but the above will work too.
You can use $( document ).ready() if page 2 is a new document.
If "page 2" is at a scroll point in the same document, you can use an if statement with the scroll point using .scroll(). Add your script in the head of your new document or a link to a new js file.

Multiple jQuery document.read event handlers running in wrong order

I recently added a feature to our ASP.NET MVC web application. There's a page that is displayed when the user clicks on an item in a table. The page uses AJAX to display a partial view in a single div in the page's HTML. The partial view uses the Telerik Kendo UI to define and display dialogs and DropDownList controls. This is complicated in that the JavaScript imports are all on the View for the page, while the PartialView just builds the HTML to be displayed in the div.
The JavaScript I wrote on the page includes a jQuery document.ready event handler:
$(document).ready(
function () {
if ( $('#details-map').val() != '' )
$('#details-map').remove();
var urlTail = '?t=' + (new Date().getTime());
// Make the AJAX call and load the result into the details box.
$('#detailsbox').load('<%= Url.Action("Details") %>' + '/' + '<%: Model.Id %>' + urlTail, displayDetails);
}
)
This works fine when I run the application on my localhost. The problem appears when I deploy the page to our development server. In this case, there's an additional document.ready event handler that's emitted to very end of the page by the Telerik Kendo / ASP.net MVC extensions:
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function(){
if(!jQuery.telerik) jQuery.telerik = {};
jQuery.telerik.cultureInfo=...;
});
//]]>
</script>
On this page, the $(document).ready event handler I wrote runs before the Telerik handler, and my code clearly depends on the Telerik handler running first. When mine runs first, I get a JavaScript error that says "jQuery.telerik.load is not a function'.
Since this does not happen on my localhost, how do I make sure that the second document ready event handler is run first?
Edit:
After more research, I've found that the problem is that the two scripts mentioned in my answer, which are supposed to be written to the page via the following line in the Master Page used by my page:
<%= Html.Telerik().ScriptRegistrar().Globalization(true).jQuery(false).DefaultGroup(group => group.Combined(false).Compress(false)) %>
Are not being loaded. In other words, the above line does nothing. It works on another page that uses the same Master Page, though. I've placed a breakpoint on the line and it is executing. Does anyone have any ideas?
You're either going to have to make it show up after the second one on the page OR do something I hate to suggest:
$(document).ready(function() {
function init {
/* all your code that needs to be run after telerik is loaded */
}
if ( $.telerik ) {
init();
} else {
setTimeout(function check4telerik() {
if ( $.telerik ) {
return init();
}
setTimeout(check4telerik, 0);
}, 0);
}
});
So, if $.telerik is loaded, it runs, otherwise it polls until it's set, and when it is set, it runs the code. It's not pretty, but if you don't have more control, it's probably your only option, unless $.telerik emits some kind of event that you can hook into.
After spending a few hours working on this, I finally got it to work. The problem turned out to be that two JavaScript files that are used by the Telerik DropdownList control and Window control were not being loaded.
In spelunking through the JavaScript on the page, I came across this script that was generated by Telerik:
if(!jQuery.telerik){
jQuery.ajax({
url:"/Scripts/2011.3.1306/telerik.common.min.js",
dataType:"script",
cache:false,
success:function(){
jQuery.telerik.load(["/Scripts/2011.3.1306/jquery-1.6.4.min.js","/Scripts/2011.3.1306/telerik.common.min.js","/Scripts/2011.3.1306/telerik.list.min.js"],function(){ ... });
}});}else{
jQuery.telerik.load(["/Scripts/2011.3.1306/jquery-1.6.4.min.js","/Scripts/2011.3.1306/telerik.common.min.js","/Scripts/2011.3.1306/telerik.list.min.js"],function(){ ... });
}
This script was emitted by a call to Html.Telerik.DropdownListFor() in my partial view. I'm guessing that the code to include for the two JavaScript files mentioned in the code, telerik.common.min.js and telerik.list.min.js, was not emitted since the call was on a partial view. Or I was supposed to include them all along & didn't know it (I'm very new to these controls). Oddly, everything worked when I ran it locally, so I don't get it.
In any case, I added two <script> tags to my View to include these files and everything started working. That is, I added the following tags to my page:
<script type="text/javascript" src="../../Scripts/2011.3.1306/telerik.common.min.js"></script>
<script type="text/javascript" src="../../Scripts/2011.3.1306/telerik.list.min.js"></script>
Live and learn.

pageLoad function in master page and content page

I have a pageLoad js function in master page,
and another one inside content page.
Does the first one (in master page) prevent the second one (in content page) from firing ?
It's the other way round. The one on the Content Page will be fired first. To know if one is messing with the other, simply debug it on Firebug or even on Visual Studio.
You can use the jQuery syntax to chain functions to run on page load in both Master and Child pages like this:
$().ready(function() {
// Do stuff
}
Contents will be execute in the order that the appear on the page, from top to bottom.
You could force items to be run in a specific order with a construct like this in your MasterPage:
<script>
$().ready(function() {
// Do MasterPage stuff
if (onChildPageLoad) onChildPageLoad();
});
</script>
and in the child page place a script block like this:
<script>
var onChildPageLoad = function() {
// Do childpage stuff
}
</script>

Dynamically loaded javascript doesn't work second time loaded

I am working on a webpage that uses a JQuery UI dialog (in modal mode) to display a form that is dynamically generated using Django. The basic flow is:
the user clicks a button
jquery (using AJAX) issues a get request that returns the html for the form which is then used to fill the dialog
The html contains a script tag that handles some UI on the form which loads fine and works as expected
the user than fills out the form and clicks "Done" and the form is submitted.
The issue comes in when the user makes an error on the form. The server responds to the post request (that submits the form) with the original form (including the script) modified to show the errors. This second time the script is loaded it gets a "Uncaught ReferenceError: $ is not defined (anonymous function)" The script is exactly the same as before when it worked fine. To be clear throughout this entire process the page is never refreshed.
Here is the gist of the javascript that takes care of the modal:
var add_container = $("#add_container");
add_container.dialog({...})
function show_form(form,response_func) {
add_container.html(form);
add_container.dialog("open");
$("#add_form").submit(function (event) {
return submit_form($(this),response_func);
});
}
function submit_form(form,response_func) {
add_container.append('<p>Adding...</p>');
//this is a trick to upload a file without reloading the page
form.attr('target','upload_target');
$('#upload_target').load(function() {
var response = $('#upload_target').contents().find('body').html();
add_container.dialog("close");
resp_obj = $(response)
if (resp_obj.is('form')) {
//***this is what reloads the form when there is an error
show_form(response,response_func);
} else {
response_func(resp_obj);
}
});
}
$('#add_link').click(add_link);
function add_link() {
$.get('/add_link', function(data) {
function add_response(response) {
//handle successful submission
}
show_form(data,add_response);
});
}
//...more stuff that is not important
This is the gist of the html returned from /add_link
<script type="text/javascript" src="/scripts/add_form.js" ></script>
<form id="add_form" enctype="multipart/form-data" action="/add_link/" method="post">
<!-- Dynamically generated form here !-->
</form>
The add_form.js is a pretty standard javascript file that uses jQuery. Its starts with $(document).ready(function () {...} ) and the first $ is where the ReferenceError occurs
The form needs to be dynamically generated based on what is clicked so I can't just put everything statically on the page. The script is not dynamically generated so it doesn't necessarily need to be dynamically loaded but I wasn't sure how to keep it in its own file, and also only have it run when the form is loaded. I am open to suggestions of alternative ways to accomplish the same effect.
Your form action is pointing to a different relative path to the one containing the jQuery framework script, etc.
<script type="text/javascript" src="/scripts/add_form.js" ></script>
<!-- src="/scripts" -->
<form id="add_form" enctype="multipart/form-data" action="/add_link/" method="post">
<!-- action="/add_link" -->
To make sure it's loading the framework after the form submission, just use something like the developer tools on your browser and check the head tag for the jQuery script src. Is it still there?
Thanks to MelanciaUK I realized that when I submitted my form to the iFrame the response was getting sent first to there where the script would run and error because the iFrame is treated as its own page and doesn't have access to jQuery loaded on the main page.
I decided to solve the problem by eliminating the dynamic loading of the add_form script and simply load it when the page loads just like all my other scripts. I created a custom jQuery event (using .trigger) in order to only have the script run when the add form is opened. This worked exactly the way I wanted it to.
Hope this helps anyone with a similar problem. If you have any questions feel free to ask!

Categories

Resources