Best method of adding this javascript to Asp.Net website? - javascript

I have a couple of small javascript functions:
// Show cookie notice
$('#site-cookie-notice').slideDown();
// Hide cookie notice
$('.close-cookie-notice').click(function (e) {
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
$('#site-cookie-notice').slideUp();
});
The functions are only relevant to a single user control, that appears a maximum of once in a user visit (not at all for returning customers). The rest of the time the control is not rendered.
The above code currently resides in my global.js, inside the document.ready function, so loads every page, however it seems like this is wrong an uneccessary use of resource.
I'd be interested to know if there is a better approach to registering this code on such an adhoc basis.

You can use the ScriptManager class to register scripts in the load of your user control. This can also be used to ensure that the script isn't loaded more than once.
You can use either RegisterClientScriptBlock or RegisterClientScriptInclude depending on whether you want to provide the script in-line or have it in a separate file.

Use the ScriptManagerProxy in the user control to reference this script. That will include it on your page without having to have it on all pages.
This requires a ScriptManager or ToolkitScriptManager (if using AjaxControlToolkit) on your master page or content page. You can only have one script manager per entire rendered page.
http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanagerproxy.aspx

Related

How to stop scroll event function when the user move to another page

I am adding the scroll event in javascript for one of my pages. The code is like this:
document.getElementById("myProject").addEventListener("scroll", myFunction);
function myFunction() {
document.getElementById("scrollEvent").innerHTML = "These are all my projects so far";
}
So, when users start scrolling, they will see a text "These are all my projects so far".
My problem is how to stop showing this text when users move to another page.
Please help ( I am a verrrry fresh developer)
Thanks so much
A few thoughts.
Without knowing your dev environment (e.g. are you using MVC with a framework?), I will assume you are simply talking about separate/individual HTML pages.
Each HTML page can have its own javascript. Just like HTML and CSS, there is no need to have the same javascript functions on every page. (You don't have the same HTML content on every page, right?) Usually, we divide up the javascript into multiple files - some files are added to every page, some are specific to a certain page. It is easiest to have one (external) javascript file that you reference on every page, and then specific javascript code for each page - either in a second external file that is referenced, or on the HTML page inside <script>//js here</script> tags.
If the DIV with ID myProject is not on the other page, then the javascript won't do anything. However, it is not good to have broken javascript on a page, so make sure it is not included on other pages.
If you are using a framework, like CodeIgniter or ReactJS or Angular, please tell us so we can adjust our answers accordingly.
If the case is a switching between browser tabs, you can use two different events like below.
$(window).blur(function(e) {
// stop scroll event, when switching to another tab
document.getElementById("myProject").removeEventListener("scroll");
});
$(window).focus(function(e) {
// start scroll event
document.getElementById("myProject").addEventListener("scroll", myFunction);
});
I am not sure what you are actually looking for, because when user switch between tabs, he can not see the text anymore no matter there is a scroll event or not. If you are concern about performance, then the above solution would help.

How to call a javascript from plugin or refresh the page in microsoft dynamics 2015

We have a requirement in which we have to call a Javascript from plugin,
also we want to refresh our page from plugin.
Is there any way to do this? We know this can be done from javascript using XRM but we need to refresh our page after plugin execution so for the same we will need a call to javascript from plugin or any other way to refresh our page from plgin.
We cannot make our plugin as synchronous.
One solution could be to set an attribute on the regarding entity in the plugin execution that indicates, that the process finished.Then let a javascript run, which checks this attribute periodically and performs the refresh.
One solution is to override the Save button's default functionality and call you custom code (js function) when user clicks the save button.
function customSave()
{
Xrm.Page.data.save().then(
function(){
Xrm.Utility.alertDialog("Record saved");
Xrm.Page.data.refresh();
},
function(error){
Xrm.Utility.alertDialog(error.message);
});
}
Correction: I just saw you have mentioned that your plugin will run ASync... This solution will not work.

Call a function after every updatepanels partial postback event, on the page

I am working on a custom control that is being used on a webpage that contains many updatepanels. In my custom control, there is extensive use of jquery and many plugins are used as well. Now, on every updatepanel's postback, THE CONTROL GETS RENDERED AGAIN AND AGAIN, it loads the javascript resources again too, but doesnt call the javascript functions again. This is causing problem that many elements in my control which has to be turned in to one thing or another by jquery plugin are not working(javascript functions not calling in simple).
Now I have tried many solutions, including the ones mentioned in this question
How to have a javascript callback executed after an update panel postback?
but in vain. Previously, when my page contained only one updatepanel,
pageLoad(sender, Args);
functon was working fine, now in the case of multiple updatepanels that is not working, neither
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
function pageLoaded() { }
If you don't want your control to refresh on every UpdatePanel's postback - set UpdateMode for the UpdatePanel that hosts your control to Conditional this way it will be refreshed only when its own trigger or child control fire (Ref: http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.updatemode(v=vs.90).aspx).
That said, you don't have to manually add pageLoaded event handler on client side. Use intristic pageLoad function which fires on every page load be it via UpdatePanel or otherwise (Ref: http://msdn.microsoft.com/en-us/library/bb386417(v=vs.90).aspx)
One other way to fire a JS function is from server-side code. Every time your control loads or performs some server-side init - use ClientScript.RegisterStartupscript call to make sure JS function will be called on the client afterward, for example
ClientScript.RegisterStartupscript(this.GetType(),"myFunc", "myFunction();", true);
Ref: http://msdn.microsoft.com/en-us/library/z9h4dk8y(v=vs.90).aspx

ScriptManager duplicates javascript

I have a usercontrol that can be used in for example a gridview itemtemplate, this means that the control might or might not be on the page at page load. In the case where the control is inside an itemtemplate i will popupate the gridview via asynchronous postbacks (via updatepanels).
The control itselfs registrers scriptblocks since it is depending on javascripts. First i used
Page.ClientScript.RegistrerClientScriptBlock
But this doesn't work on asynchronous postbacks (updatepanels) so i then tried the same using ScriptManager which allows me to registrer scripts on the page after async postbacks. great!.
ScriptManager.RegisterClientScriptBlock
However, ScriptManager (what i know of) does not have the functionallity to see if a script already is on the page, so i will for every postback generate duplicates of the script blocks, this is ofcourse unwanted behaviour.
I did a run at Google and found that i can call the Dispose() method of the PageRequestManager can be used, this does work since it clears the scripts and then adding them again (this also solves my issue with removing unused script blocks from removed controls).
Sys.WebForms.PageRequestManager.getInstance().Dispose()
However, ofcourse there is a downside since im posting here :).
The Dispose() method disposes the instance on the master page as well which leads to scripts running there will stop to function after an async postback (updateprogress for example).
So, is there a way to check if a script already exists on the page using ScriptManager or any other tools, that will prevent me of inserting duplicate scripts? Also, is there a way to remove certain script blocks (when i am removing an item in itemtemplate for example).
Big thanks in advance.
Try a function like this one:
Public Sub AddScriptToCompositeScriptSafety(ByRef manager As ScriptManager, ByRef script As ScriptReference)
For Each item In manager.CompositeScript.Scripts
If (item.Path = script.Path) Then
Return
End If
Next
manager.CompositeScript.Scripts.Add(script)
End Sub
If you set the same type and key attributes when registering then I think the SM will include only one of these.

How do I do ajax navigation on pageload?

I have a page with several reports that are produced via ajax calls. I am prototype.js framework on this page for some of the display functions.
The links for each report have anchors/tags like #Report1, #Report2 etc, which are hrefs with onClick functions that do lots of work to create the report via javascript.
I would like to make it so if a user bookmarks a page with a link or navigates directly with a anchor/link in the url for my page to load the report.
So if the user goes to : http://mysite/myPage.jsp#Report2 it should load the page and go to the 2nd report.
Is there anyway in my pageload I can look at the anchor/link and perform the onlcick for that anchor? I was thinking I could create a big case/if statement to figure out what to do, but maybe there was an easier way.
It all depends on how you're Ajax calls are structured really. I do something similar for opening the correct tab within a tab navigation. The code would start off like this, if you let me see how your Ajax events are hooked up then i should be able to show you the rest.
document.observe("dom:loaded", function() {
if(window.location.hash){
var report = window.location.hash.replace("#","");
}
});
EDIT
Looking at your code you would be much better off (imv) switching to an unobtrusive method where you attach events to your elements e.g.
$('ele').observe('click',doStuff.bindAsEventListener($('ele')));
This would enable you to more easily connect the same functionality to a click or a pageload but is also better practice anyway and would prevent code duplication etc. Obviously this is missing large chunks but hopefully you get what i mean

Categories

Resources