I am building a cms in C# (.NET) and all content is stored in the database. This includes on-page css and on-page js code. The issue I have is that the handler that loads the js script is processed before the page template so if the js includes any jquery object commands, they throw an error because jquery itself has not been loaded and initialized yet.
For example, my template has a line on the master page near the top like...
<script src="/scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
as you might expect. Then, further down I load page-specific js code like this:
<script type="text/javascript" src="/Handlers/ServeJsByID.ashx?pgsid=<%=pgsID %>&jsid=<%=jsID %>"></script>
where pgsID is the id of the current page and jsID is the id of the javascript record I want to load.
I assume this has something to do with the lifecycle of the .NET page but I have no idea how to force the js load through the handler to occur AFTER the page has already loaded and processed the jquery.js file.
I tried using Page.ClientScript.RegisterStartupScript in the code behind but still get 'Object Expected" errors.
How can I load javascript in code behind and have it processed AFTER the jquery file is loaded?
If you try this:
$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function() {
$("#go").click(function(){
$(".block").animate( { backgroundColor: "pink" }, 1000)
.delay(500)
.animate( { backgroundColor: "blue" }, 1000);
});
});
http://api.jquery.com/jQuery.getScript/
Related
I have a certain asp.net page where I am loading the content into a using a javascript.
Basically it is like loading a content from a third party.
And I have an image which should be loaded after the javascript generates the content in
But currently what happens is the image is showing before the content is loaded into div, which is bit in appropriate. Could you please suggest me a method to do the other way around.
I have put a code sample with this.
In aspx page.
<body> <div id="bodyDiv" runat="server">
<script src="//platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/CompanyProfile" data-id="xxxxx" data-format="inline"></script>
<a id="closeLink" href="http://www.xyz.com" class="closedbutton" runat="server"> <img id="closeImg" runat="server" src="images/remove.png" /></a>
</div></body>
What method should I use to load the image after the content from javascript is loaded.
Thanks !
Your image is loading with your page. You could hide that image and make it visible after some delay after document is loaded. And as you have referenced script they will load along with your HTML and when DOM will load, So you could use setTimeout and set some delay to load your image. And load image after document is load see below example.
$(document).ready(function () {
window.setTimeout(function () {
// Your Image code goes here
// Set image display:block in this code block
// for example $('img').css('display','block');
}, 2000);
});
You could use a conditional script loader like http://yepnopejs.com/ and then use the following options after the third party scripts are loaded.
You can hide the link (using css display: none;) then show it using JavaScript at the end of your loaded scripts:
document.getElementById("closeLink").style.display="block";
Or you can dynamically add the link to the page after your scripts have ran using either .appendChild() or .innerHTML(). If using JQuery you can do the following:
$(body).append('<a id="closeLink" href="http://www.xyz.com" class="closedbutton"> <img id="closeImg" src="images/remove.png" /></a>');
I would also look to see if the 3rd Party script has a callback function you can hook into when its loaded.
Hello i need to stay on a jquery tab after asp.net postback, but nothing what i found here or somewhere else in the web works for me.
I tried:
Staying on current jQuery tab across post back?
and
Jquery postback, maintain same tab after postback
but also some other sources.
Everytime when im changing
$("#tabs").tabs();
to something like:
$(function () {
$("#tabs").tabs({
show: function() {
var selectedTab = $('#tabs').tabs('option', 'selected');
$("#<%= hdnSelectedTab.ClientID %>").val(selectedTab);
},
selected: <%= hdnSelectedTab.Value %>
});
});
With hiddenfield etc. i get this error 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'tabs'.
When im Using the jquery.cookie.js file with this code:
$("#tabs").tabs({ cookie: { expires: 1 } });
i dont get an error but i dont stay on the tab after postback.
You can give your input button a css class.
#inputField {
display:none !important;
}
Save this as yourCssClass.css
document.getElementById("inputField ").className += "yourCssClass";
Add this to your JavaScript
I found out what the Problem was, I inserted jquery on the end of my master page because of that somehow it overwrote the jqueryui file in that specific aspx file. After i added the jqueryui.js file after the jquery.js everything worked fine.
I have a ASP .Net MVC4 Web application. In it I have my usual html for the _Layout.cshtml, which in turn loads the default Home/Index. All works fine.
In my index I am also loading a partial view. This works fine too. No probs.
I am using a the UI tools from the following site:
http://www.keenthemes.com/preview/index.php?theme=metronic
The problem is it seems to be primarily HTML4 and not designed for MVC out of the box so I am having to tweak it slightly to get it to work the way I want. (Nothing beyond anything very basic). For example, moving one part out to the index and using Renderbody() to load it so the actual html structure never changes. I have done this a million times to be sure I am not missing any closing tags or anything else that could cause my problem.
Up to this point there is no problem at all. Everything loads as it should.
I continued to create a 2nd View and its partial to extract other parts of the site. As usual, baby steps first. Before extracting any other code, I just used a little "Hello World" in the first page, and a similar string in the partial to be sure it was working. It was.
Now when I type in the url Home/ActionName the whole thing reloads as it should but looks horrible. and I get this error message:
0x800a1391 - JavaScript runtime error: 'jQuery' is undefined
Below is my code which clearly defines it:
<!-- BEGIN CORE PLUGINS -->
<script src="assets/plugins/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function ()
{
App.init(); // initlayout and core plugins
_Layout.init();
_Layout.initJQVMAP(); // init index page's custom scripts
_Layout.initCalendar(); // init index page's custom scripts
_Layout.initCharts(); // init index page's custom scripts
_Layout.initChat();
_Layout.initDashboardDaterange(); //Red date range
_Layout.initIntro(); //Pop up messages
});
</script>
It points me to the jQuery(document).ready part when I see the message.
Again, when I load the page normally, it works fine. When I type Home on its own it works fine. Its only when I type Home/AnythingElse that it gives this error message. Even if I type Home/ which should load in the Index file, it gives me this error message.
jQuery is defined, so why is this happening on postback?
Any help is appreciated.
Try setting the src for jQuery to be absolute from the site root:
<script src="/assets/plugins/jquery-1.8.3.min.js" type="text/javascript"></script>
Note the / before assets - when your src path does not start with a / the browser will try and load the asset relative to the current path, so in your example when you add the trailing slash to Home it will try to load jQuery from Home/assets/plugins/...
For me, the MVC bundlers were causing problems (in my case the ui bundler)
Here is the order which worked for me.
<script src="/Scripts/modernizr-2.5.3.js"></script>
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/bundles/jquery-ui"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
You need to add the jquery-x.xx.x.js first before the validate.js like this
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
Within my C# code behind page, I have the following:
MembershipUser currentUser = Membership.GetUser(false);
HttpContext.Current.Session["UserGuidAsString"] = currentUser.ProviderUserKey.ToString();
At the bottom of the corresponding ASPX page, I have the following code:
</form>
<script type="text/javascript"> var userGuidAsString = '<%=Session["UserGuidAsString"]%>';
alert(userGuidAsString);
</script>
</body>
</html>
It gives the proper expected result which is an alert box with the User's GUID when I run the page
I wanted to move the JavaScript code to a .js file so that the code is more modularized and organized.
I created the following test.js javascript file with the following contents:
var userGuidAsString = '<%=Session["UserGuidAsString"]%>';
alert(userGuidAsString);
I also modified the ASPX page so that it would include the test.js javascript file:
</form>
<script src="/Scripts/test.js" type="text/javascript"></script>
</script>
</body>
</html>
It fails because it just gives an alert box with
'<%=Session["UserGuidAsString"]%>'
as a message
May I please know how I can make in line server C# code work within JavaScript .js files?
By This your accessing Server Variable
'<%=Session["UserGuidAsString"]%>'
its not functionlity of Javascript.
You can write this code without js block also..
its like ASP code..
so its workg with .aspx page only not in javascript
A common workaround for this is to put the server variable in an html hidden element. For example:
<input type="hidden" id='guid' value='<%=Session["UserGuidAsString"]%>' />
Then your javascript file:
var guid = document.getElementById("guid").value;
Or, you could define a js variable in your html, and reference that in your js file. Just make sure to declare the variable before you reference it.
<script type="text/javascript">
var guid = '<%=Session["UserGuidAsString"]%>';
</script>
<script type="text/javascript" src="yourScript.js></script>
Then in your js file you can simply use the guid variable.
In order for C# to get executed on the server before the .js file reaches the client, you'd have to register that page extension in IIS so that the asp_net .dll processes .js files.
In your particular case (handling GUIDs), you really don't want to go this route, because with the nature of .js file caching, you're going to have a lot of problems ensuring that it's a fresh version being served up every time.
I suggest recreating a very simple (and yes, modular/reusable) JS function that makes a call to, say, GetUserGuidAsString.aspx by using AJAX or the equivalent.
I have a drop down list and some styles applied to it from two js files, included in head like:
<script type="text/javascript" src="js/functions.js"></script>
<script type="text/javascript" src="js/jquery.jqtransform.js"></script>
All it's working great when the page is loading for the first time.
But when i do an ajax request on this page the styles applied before, are lost, so i have included the js src files from the code behing like:
protected void Page_PreRender(object sender, EventArgs e)
{
loadJs();
}
private void loadJs()
{
ScriptManager.RegisterClientScriptInclude(this,
typeof(Page),
"AlertScript",
ResolveClientUrl("~/Site/js/jquery.jqtransform.js"));
ScriptManager.RegisterClientScriptInclude(this,
typeof(Page),
"AlertScript2",
ResolveClientUrl("~/Site/js/functions.js"));
}
But...it's still not working although i see in the broswer - view source that the js files are loaded correctly in the body...
Do you have any suggestion?
Thanks in advance.
In your ajax return function (on the html page) you need to reapply the jquery commands you run the first time the page loads.
jQuery runs over the DOM and does what you tell it to. When the ajax call returns and replaces a part of the page, all runtime changes for that region are lost, so you need to reapply them.
Basically you need to call whatever function is called in jqtransform.js and in functions.js on page load on the html element which is replaces.