I am creating an ASP.NET custom control.
I want to set the body onload event of the ASPX page where the control resides.
Please note I cannot rely on the body tag in the ASPX page having runat="server".
any ideas??
Cheers.
Inline javascript! Just incase you can't use jQuery
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
} } }
addLoadEvent(initialize);
link to read http://www.webreference.com/programming/javascript/onloads/
Credits goto http://simonwillison.net/
If you include jQuery in your project you can use this:
jQuery(document).ready(function ()
{
// page load code here
});
You can run these multiple times on a page, ie handy within a control
Try this,
<script type="text/javascript">
window.onload = initialize();
function initialize() {
//your stuff
}
</script>
Related
My mvc view layout is null. how can i add script inside view.
#{
Layout = null;
}
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$('#txtChild1').on('change', function () {
$("#C1Age1").show();
});
});
</script>
}
Error show
cannot resolve section 'Scripts'
If you use Layout = null then you don't need to use #section Scripts any more. you can simply use script tag.
Example:
#{
Layout = null;
}
<script type="text/javascript">
$(document).ready(function () {
$('#txtChild1').on('change', function () {
$("#C1Age1").show();
});
});
</script>
If you are not using layout page then you need not to add section. add scripts as you add them on a html page.
#{
Layout = null;
}
<script type="text/javascript">
$(document).ready(function () {
$('#txtChild1').on('change', function () {
$("#C1Age1").show();
});
});
</script>
You can also add script block without section if it is not mandatory.
I am adding youtube video to a companies website and would like them to display on non-flash devices. I have been playing with the youtube iframe API and updated one of their examples to allow a user to click on a link to change the video in the iframe. The edited code is:
<!DOCTYPE HTML>
<html>
<body>
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'JW5meKfy3fY',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
evt.target.playVideo();
}
function onPlayerStateChange(evt) {
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
function loadVideo(videoID) {
if(player) { player.loadVideoById(videoID); }
}
</script>
Click me to change video
</body>
</html>
The only thing I added was:
function loadVideo(videoID) {
if(player) { player.loadVideoById(videoID); }
}
This works fine in Safari, Chrome and Firefox but does not work in IE7, 8 or 9. In IE7 and 8 it returns an error "Object does not support this property or method".
Is this an issue with the API or am I doing something wrong?
I had a similar problem, and it turned out that you shouldn't call any of the methods on the YT.Player object (including loadVideoById) as long as onPlayerReady hasn't been called.
Doing a check if(player) {...} isn't sufficient, the Player object will be created and some properties will already be available in out without the methods you need being available.
You will need to call the load video function from the onPlayerReady event.
For example, if you want to load a video when clicking a thumbnail do this (this would require jquery but it should get the point across):
function onPlayerReady(evt) {
evt.target.playVideo();
//declare the click even function you want
$('#thumbs a).click(function(){
//get a data-video-id attr from the <a data-video-id="XXXXXX">
var myvideo = $(this).attr('data-video-id');
//call your custom function
loadVideo(myvideo);
//prevent click propagation
return false;
});
}
This way you can be sure the player is loaded.
Preventing click propagation with return false after the call to player.loadVideoById in my click event handler did the trick for me.
Here by adding this code my problem of getting page posted back in spite of having validation error is solved
([blog]: Jquery Validation And Update Panel Together)
but it introduced a new one, now by selecting the master dropdown list my child dropdown is not populating I have checked from code behind the targeted method to populate the child dropdown is not firing at all….
<asp:UpdatePanel ID="updRole" runat="server" UpdateMode="Conditional"> <ContentTemplate>
<script type="text/javascript" >
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest (instance_initializeRequest);
function instance_initializeRequest(sender, args) {
if (!Validator())
{args.set_cancel(true);
}
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
This piece of code I have in master page where the validator() function is fired in .ready() event fired by default but the problem was by adding update panel in any content page is method is firing(Validation error is also showing for 2 sec) but page is getting posted back .
<script type="text/javascript">
// only for demo purposes
$.validator.setDefaults({
invalidHandler: function (form, validator) {
}
});
$().ready(function () {
Validator();
});
function Validator() {
var container = $('div.container');
// validate the form when it is submitted
var validator = $("#form1").validate({
errorContainer: container,
errorLabelContainer: $("ul", container),
wrapper: 'li',
meta: "validate"
});
}
</script>
Script in the head:
<script type="text/javascript">
// only for demo purposes
$().ready(function () {
$.validator.setDefaults({
invalidHandler: function (form, validator) { }
});
var container = $("div.container");
$("#form1").validate({
errorContainer: container,
errorLabelContainer: $("ul", container),
wrapper: 'li',
meta: "validate"
});
});
</script>
Script just below the ScriptManager control:
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(instance_initializeRequest);
function instance_initializeRequest(sender, args) {
if (!$("#form1").validate().form()) {
args.set_cancel(true);
}
}
I have an asp.net button on the page. I am trying to do this:
$("#btn").click(function(e) {
e.preventDefault();
alert('hi');
}
But the alert never shows up. I have to use an ASP.NET button only and not a HTML one.
Try to have the method return false as well and in your buttons onclick you add the javascript. Like this:
$("#btn").click(function(e) {
e.preventDefault();
alert('hi');
return false;
}
or add it as an onclientclick function like this:
function ClickFunction() {
alert('hi');
return false;
}
<asp:Button OnClientClick="return Clickfunction();" />
Make sure you reference the ClientID of the button, not the "normal" ID.
$("#<%= MyControl.ClientID %>").click(function() {
alert(...);
return false;
}
Also make sure this is inside a document.ready() handler:
$(document).ready(function() {
$("#<%= MyControl.ClientID %>").click(function() {
alert(...);
return false;
}
});
Ok I got the answer over here
Using jQuery to Prevent ASP.NET Server Side Events from Occuring
I was missing the $(document).ready(function() . So silly of me!
I am trying to attach an event handler to form.submit on asp.net rendered pages with no success. I want to intercept every postback, and doc. says that I should be able. Am I doing something wrong?
$(document).ready(function() {
$("form").submit(function() {
alert('Form submit');
debugger;
});
});
Don't know if you are still looking for it, but here is the solution I have. I don't think it works with event canceling if using, say, stopPropagation() but it will let you run some script before submitting the form.
<script type="text/javascript">
$(function () {
var oldSubmit = __doPostBack;
var newSubmit = function (eventTarget, eventArgument) {
alert('custom submit function');
return oldSubmit(eventTarget, eventArgument);
};
__doPostBack = newSubmit;
});
</script>
This is something I did on a legacy WebForm application:
//trigger jquery form submit event handlers on __doPostBack
$(function() {
var oldPostBack = __doPostBack;
__doPostBack = function() {
$("form").triggerHandler("submit");
oldPostBack.apply(this, arguments);
};
});
This allows you to wire "submit" events using jQuery the way you normally would:
$("#myForm").submit(function() { alert("submitted!"); });
Typical doPostBack hijacking, but only once. It triggers "submit" handlers on any form elements before doing the old postback. This is necessary because, while asp.net does call the onsubmit function attached to the form dom object, it doesn't look like jquery's events work that way.
asp.net webforms are generally enveloped in only one big form (hence the term web forms).
if I'm not mistaken, all links and submit buttons call __doPostBack manually, so it bypasses the calling form submit and delegates that responsibility to the __doPostBack function.
you would probably need to overwrite this function.
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
though I'm trying to understand your "debugger;" line in your function. perhaps it should be this?
$(document).ready(function() {
$("form").submit(function() {
alert('Form submit');
});
});