change cursor to busy while page is loading - javascript

I understand how to use javascript to change the cursor to busy while the page is making and ajax call.
However I have a page that does not use ajax, it uses a postback to reload the page. However the load is rather data intensive and it takes a few seconds. During this time the user can still click on the page. I want to turn the cursor to "waiting" so the user does not try to click on the page.
For example I have a couple of dropdowns that cause postback. I make a selection and the page loads for 3 seconds. While it loads I would like the cursor to turn to waiting so the user does not try to make a selection on a second dropdown until the page reloads.
Is this possible?
Additional Info: (simplified version of my setup)
I have a masterpage:
<form id="form1" runat="server">
<table width = "100%" bgcolor="White">
<tr><td>
<h3><asp:ContentPlaceHolder id="MAIN" runat="server"></asp:ContentPlaceHolder></h3>
</tr></td>
</table>
</form>
<script type="text/javascript">
function cursorwait(e) {
document.body.style.cursor = 'wait';
}
var fm = document.getElementById('<% =form1.ClientID %>');
if (fm.addEventListener) {
fm.addEventListener('submit', cursorwait, false);
}
else {
fm.attachEvent('onsubmit', cursorwait);
}
</script>
and then a page that uses the master page:
<asp:Content ID="Content1" ContentPlaceHolderID="MAIN" Runat="Server">
<table runat=server id="tb_simple_search_table" cellpadding = 0 cellspacing = 0>
<tr><td>
<asp:DropDownList...
<asp:DropDownList...
</td></tr>
</table>
</asp:content>

I am not certain if this is the best or most efficient method but if you want to change the cursor to show the page is busy after the button click the following jQuery should do the trick:
$(document).ready(function() {
$(".button").click(function() {
$("*").css("cursor", "wait");
});
});

you can add a handler to the form's submit event.
CSS
.wait, .wait * { cursor: wait; }
JavaScript
function cursorwait(e) {
document.body.className = 'wait';
}
var fm = document.getElementById('<% =form1.ClientID %>');
var proxySubmit = fm.onsubmit;
fm.onsubmit = function () {
cursorwait();
if (proxySubmit) {
proxySubmit.call(fm);
}
}
here we're ensuring our method gets called if submit() is called in js like the drop down does when it causes a postback. this should also catch any other instances of the form submitting.

Just give each button a class, say "WaitOnClick", then just write it: $(".WaitOnClick").click(function() {

Related

asp.net pass value from javascript to control on a modal popup

Ok, I changed the title because I can't get anywhere with previous approach, so I'm returning to the original question: how can I pass a variable obtained through javascript to a textbox on a modal popup?
I already tried to place a hidden field and even a textbox on the parent page, inside or outside an update panel, but when I click on the linkbutton that opens the modal popup their values are resetted to default.
I already searched and tried many different ways but I can't succeed.
I have a table in a repeater and I need to know the cells selected by the user: start and ending cell of the selection. I accomplish that with this javascript:
$(function () {
var mouse_down = false;
var row, col; // starting row and column
var $tr;
$("#tblPersonale td")
.mousedown(function () {
$("#col_to").html('?');
mouse_down = true;
// clear last selection for a fresh start
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
$tr = $(this).parent();
row = $tr.parent().find("tr").index($(this).parent());
col = $tr.find("td").index($(this));
$("#row").html(row);
$("#col_fr").html(col - 1);
return false; // prevent text selection
})
.mouseover(function () {
if (mouse_down) {
$("#col_to").html('?');
if ($tr[0] === $(this).parent()[0]) {
var col2 = $(this).parent().find("td").index($(this)); // current column
var col1 = col;
if (col > col2) { col1 = col2; col2 = col; }
$("#col_fr").html(col1-1);
$("#col_to").html(col2 - 1);
// clear all selection to avoid extra cells selected
$(".highlighted").removeClass("highlighted");
// then select cells from col to col2
for (var i = col1; i <= col2; i++) {
if (col1>1){
$tr[0].cells[i].className = "highlighted";}
}
}
}
})
.bind("selectstart", function () {
return false; // prevent text selction in IE
})
$(document)
.mouseup(function () {
mouse_down = false;
});
});
So, when user selects one or more cells I have the start/end value in here:
<span id="col_fr" runat="server" enableviewstate="true">?</span>
<span id="col_to" runat="server" enableviewstate="true">?</span>
Then, when user click a linkbutton I want to use these values to write a text in a textbox on the modal popup that shows. As I said, I can't make it work, anything I tried the result is that the values are lost when popup shows, even if I assign values to global variables before showing the popup.
This is my linkbutton:
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click">
The idea behind the old question was to pass the values to the url as parameters and then in the page load use them, but then the table selection doesn't work anymore because at every selection the page refresh because of the url change.
Please anyone, I'm totally lost and not for lack of trying!
OLD QUESTION
asp.net pass a control value as parameter in onclientclick
I found similar questions but no one answer to my problem (or at least, I can't make anything working).
I want to concatenate to the url of the active page some parameters like Home.aspx?col_fr=2 where instead of the fixed "2" I want to pass the value of a hidden field. How can I achive that?
This is my current code:
<asp:hiddenfield runat="server" id="hdnColonnaDa" EnableViewState="true" />
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="window.location='Home.aspx?col_fr=2';return false;">
Thanks
It just have to move the parameter code o a javascript function like
function getURL(){
var param1 = someField.value/*get field value*/;
var url= "Home.aspx?col_fr="+ param1;
window.location= url;
return false;
}
Html
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="getURL()">
Don't use UpdatePanel or Modal popup server side. You can use a Thickbox or similar jquery plugin to open the popoup.
Popup can be an inpage div or another page. In case of page, you can easily pass parameters in the url, in case of inpage div, you can get hidden field values.
You can find jquery overlay as Thickbox: just add css and js to your site, the right class on the link and fix the url to open.
Solution using another page
Imagine to use Colorbox (http://www.jacklmoore.com/colorbox/):
PRE
Suppose you have your variable values in some hidden field in your page
TODO
include jquery in your page
Download and include css and js for colorbox
In your page add a html tag with on click event
Add a script section in your page
function openLink()
{
var hiddenValue= $("#col_fr").text(); // or .html()
var urlToOpen = "yourpage.aspx?ids=" + hiddenValue;
$.colorbox({
iframe: true,
width: "75%",
height: "75%",
href: urlToOpen
});
}
Then in Yourpage.aspx you can use url parameter "ids".
Code is not tested!
Finally I did what I want by tuning the original javascript function.
I added 3 hiddenfield on the page and then I add this bit
var hdncol_fr = document.getElementById("hdncol_fr").value;
var hdncol_to = document.getElementById("hdncol_to").value;
var hdnrow = document.getElementById("hdnrow").value;
if (hdncol_fr = '?'){
document.getElementById("hdncol_fr").value = col - 1;
document.getElementById("hdncol_to").value = col2 - 1;
document.getElementById("hdnrow").value = row;
}
This way the hidden fields values are set only when user actively select some cells, when there is a postback event the javascript function returns '?' for the 3 values, so with the added code the hidden field maintains the previous values until user select something else.

Running javascript function conditionally - Razor, HTML

Right now I have a table that's created dynamically using user selection + data. Sometimes, there are errors with the data, and I'd like to let a user know in the table.
Razor (the link takes you to ~/ControllerName/givenID)
<tr id="#givenID">
<td>#Html.ActionLink(name, someMethod, "ControllerName", new { id = givenID }, new { title = "", id = givenID })</td>
#if (errorConditions)
{
<div id="#givenID" onload="addErrorMessage(this)" data-test="ErrorMessage" style="display: none"></div>
}
</tr>
Javascript
$(function () {
//adding custom tooltip to document
$(document).tooltip();
//adding error message to standard
function addErrorMessage(element) {
var theElemOfID = document.getElementById(element.id);
theElemOfID.title = element.attr("data-test");
theElemOfID.style.color = rgb(255, 0, 0);
} });
I'm trying to add a title to the ActionLink (so it can be used by the tooltip) and also change the color of the link, but only when the the errorConditions are true.
Right now when I run, nothing happens. The addErrorMessage never calls, but all the information is in the places I expect (as in the link has the right ID, etc).
Does anyone have an idea?
onload is only supported on the <body>, but it is highly recommended that you do not use inline event handlers!
Use an inline script, like this (using jQuery since you seem to be using it):
#if (errorConditions)
{
<div id="#givenID" data-test="ErrorMessage" style="display: none"></div>
<script>
$(function() {
addErrorMessage($('##givenID'));
});
</script>
}

fontSize change javascript last less than 1s

I'm trying this:
</script>
<form action="ej3a.html" onsubmit="Pantalla(this.elements[0].value)">
Select word size <input type="text" name="Tletra" id="letra"><br>
<script>
Then, I send the information summited to a js method
function Pantalla(x){
if(x=="Grande")
{
document.getElementById("todo").style.fontSize="120%";
}
if(x=="Normal")
{
document.getElementById("todo").style.fontSize="medium";
}
if(x=="Pequeño")
{
document.getElementById("todo").style.fontSize="80%";
}
}
but, when I summit "Grande" it just increases for a second and later returns to normal size
Note: Forget onmouseover, the change i try to make is on a fielset, which has all text of the web page
<fieldset onmouseover="estiloof()" id="todo">
Try
return = false;
at the end of the function to prevent form submission and page reload.

How to disable/enable asp.net timer control using Javascript?

How to disabled/enabled asp.net timer control using Javascript?
My code is: (but not working)
function timeroff()
{
var b = document.getElementById('Timer1');
if (b) {
b.disabled = true;
}
}
function timeron() {
var b = document.getElementById('Timer1');
if (b) {
b.disabled = false;
}
}
This allows a user to toggle an ASP timer control using ONLY JavaScript.
I'm expanding this, but for now, it's working great ... if I want to disable the timer and not have the update panel refresh while working, it's great, not elegant yet, but it works.
Note, this works with an update panel and a timer named ID=tmrFillAlerts (see below code) ... I'm listing the most basic required ... I took out the CSS and formatting so it would be easier to follow but with all that included, it looks like this ...
The toggles look like this when page loads and you click the user button with timer running ...
Then, after clicking "Turn updates OFF" above, you see this and the timer is stopped ...
You can see the "Turn updates OFF or ON" above are in the code below as ID=lblFlyOutTimerStatus below. Also, the RED ON/OFF ball above is below as ID=lblAlertsTotal.
When the updates are ON ... and you click on the Bell or the Info button, you get a flyout like this thanks to the timer and it is updated every 60 seconds in my case (this shows the bell flyout)
The Code Behind C# ...
// Loads the DataList from the TIMER component
private void udpAlertBar(object sender, EventArgs e) {
// Do whatever you want here on timer tick ...
// Write the last BELL alert time...
lblAlertTime.Text = "Last update time:<br/>" + DateTime.Now.ToString("MM/dd/yyy hh:mm:ss tt");
// Load the BELL and INFO icon drop down lists
FillBellInfoDataLists();
// Update red alert ballz ....
UpdateAlertBallTotals();
}
The ASP page code ...
<asp:UpdatePanel id="udpAlertItemUpdater" runat="server">
<ContentTemplate>
<!-- NOTE: The update panel must wrap just this area (UPDpnl kills the javascript for some reason otherwise) -------->
<asp:Label id="lblTimerState" runat="server" Text="on" />
<ul>
<li>
<a href="javascript:void(0)" onclick="toggleUpdateTimer()">
<asp:Label ID="lblFlyOutTimerStatus" runat="server" Text="Turn updates OFF" />
</a>
</li>
</ul>
<asp:Timer ID="tmrFillAlerts" runat="server" OnTick="udpAlertBar" Interval="60000" Enabled="true"/>
</ContentTemplate>
</asp:UpdatePanel>
The JavaScript Code ...
<script type="text/javascript">
function toggleUpdateTimer() {
// Gets the timer control on the page named “tmrFillAlerts”
var timerState = $find(“tmrFillAlerts”);
// Gets the label I use for an alert ball on an icon on the page …
var timerStatusRedAlertBall = document.getElementById(‘lblTimerState’);
// Gets the menu item I have on the alert icon that drops down when clicked …
var timerStatusFlyOutLabel = document.getElementById(‘lblFlyOutTimerStatus’);
// Toggle the timer when the menu item is clicked ….
if (timerState.get_enabled() == true) {
stopUpdateTimer(); // NOTE: stop the timer, then disable …
timerState.set_enabled(false);
timerStatusRedAlertBall.innerHTML = “OFF”;
timerStatusFlyOutLabel.innerHTML = “Turn Updates ON”;}
else {
timerState.set_enabled(true); // NOTE: Enable the timer, then start ….
startUpdateTimer();
timerStatusRedAlertBall.innerHTML = “on”;
timerStatusFlyOutLabel.innerHTML = “Turn Updates OFF”;}
}
function stopUpdateTimer() {
var timer = $find(“tmrFillAlerts”);
timer._stopTimer();
}
function startUpdateTimer() {
var timer = $find(“tmrFillAlerts”);
timer._startTimer();
}
</script>
I stripped out everything but the relevant items to get it working ... otherwise this would have been ten pages long!!
Works for me in all browsers at present from an IIS 8.5 running .NET ver: 4.0.30319.42000
It's a work in progress, that was quickly done, but found some cool stuff out there I thought I'd share. Hope it helps!
Good luck!!
The following works as long as the timer is not on a Master page because you will get an error stating "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).]" when you put this javascript in the header of a Master page.
function enableTimer() {
var timer = Sys.Application.findComponent(‘<%= Timer1.ClientID %>’);
timer.set_enabled(true);
}
function disableTimer() {
var timer = Sys.Application.findComponent(‘<%= Timer1.ClientID %>’);
timer.set_enabled(false);
}
see: http://weblogs.asp.net/andrewfrederick/controlling-the-asp-net-timer-control-with-javascript for more details

Ajax callback refresh div

I implemented a Ajax callback function to update a div (announcement) in my web page.
It works fine, but the current issue is that the Ajax call function update the announcement div, however, after rewrite the content, the Javascript functions in this content are not load it. Therefore, my toggle function in table does not work after update content.
My ajax call function
setInterval("_checkUpdate()", 2000); //2 seconds one call.
function _checkUpdate() {
var callback=new Object();
callback.success=this.checkUpdateonExternalSuccess;
callback.failure=this.checkUpdateonExternalFailure;
YAHOO.util.Connect.asyncRequest('GET' , '/ci/ajaxCustom/ajaxCheckUpdate',callback);
};
On success, it update the content to rewrite to my Div
function checkUpdateonExternalSuccess (o){
if(o.responseText!==undefined) {
var str=o.responseText;
if(str !== 'nocontent') {
document.getElementById('updateContent').innerHTML=str; (Write the new content to my div)
location.reload(); //Reload the whole page, i do not want that
}
}
};
It works, it write the new content with Javascript, but the Javascript functions are not load it.
Javascript:
$(document).ready(function() {
//First hide all the contects except the headcontent
$(".content").hide();
$(".headContent").show();
//If user click on the head title, it hide/show content
$(".headTitle").click(function () {
collapseHeadContent();//reset all
var aParentTD= $(this).closest("td");
var aHeadContent = aParentTD.find (".headContent");
aHeadContent.toggle();
});
// If uses click on the title, it has toggle event for the content
$(".title").click(function () {
collapseContent(); //First reset all
var aParentTD = $(this).closest("td");
var aContent = aParentTD.find(".content"); // Content in the same TD with Title
aContent.toggle();
});
});
function collapseContent() {
//find the Head content to hide and reset of content
$(".headContent").hide();
$(".content").hide();
}
function collapseHeadContent() {
$(".content").hide();
}
HTML:
<div id="annoucementTableDiv">
<table id="annoucementTable">
<tbody id="tdContent">
<tr>
<td><span id="tdtitle"><a class="headTitle"> Forbidden: Error 403</a></span> <br />
<span class="annfrom">PLC team - 19/08/2010 at 10:30<br /> </span>
<br />
<span class="headContent"><P>Due to scheduled maintenance, HOME showed the error 403:<br/>
This is now resolved and customers can update again as normal </P>
</span>
</td>
</tr>
</tbody>
<tbody id="tdContent">
<tr>
<td>
<span id="tdtitle">
<a class="title">Downloading maps</a>
</span> <img src="/euf/assets/themes/standard/images/layout/important.png" class="alert_icon" alt="alert"></img><br />
<span class="annfrom">Sent by 2nd line - 05/11/2009 at 15:30<br /> </span>
<span class="content">Since this morning it has been reported that multiple customers are again receiving this error message.<br /><br />This error has been escalated to the relevant teams with the highest priority and is currently being looked into.
An estimated time for a fix is not yet available but we will keep you updated.
</span>
<br />
</td>
</tr>
</tbody>
</table>
</div>
If I do location.reload, the Javascript functions work. But I do not want to refresh the page.
Any ideas?
Since you're also hiding/showing things, I recommend you change you're ready handler into a named function then call it on document.ready, like this:
function loadFunc() {
$(".content").hide();
$(".headContent").show();
}
$(function() {
loadFunc():
$(".headTitle").live('click', function () {
collapseHeadContent();
$(this).closest("td").find(".headContent").toggle();
});
$(".title").live('click', function () {
collapseContent();
$(this).closest("td").find(".content").toggle();
});
});
This also uses .live() to set your click functions up once. Then when you do your AJAX load, you can just call loadFunc again to do hiding/showing or any other work, like this:
function checkUpdateonExternalSuccess (o){
if(o.responseText!==undefined) {
var str=o.responseText;
if(str !== 'nocontent') {
document.getElementById('updateContent').innerHTML=str;
loadFunc();
}
}
};
Sounds like you need the live function. It is quite straight forward.
$('.title').live('click', function() {
collapseContent(); //First reset all
var aParentTD = $(this).closest("td");
var aContent = aParentTD.find(".content"); // Content in the same TD with Title
aContent.toggle();
});
Basically adds the click handler to all title elements. Even if another loads the event is still associated with it. You can use this for all elements that are loaded by AJAX during the life of the page. So you do the same for the head element and so on.
In a project I'm writing at the moment, I insert HTML and Javascript content separately. The HTML is inserted as usual into innerHTML. And I got the javascript in a JS file which I load into my document during runtime like this:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'myJavascriptFile.js';
headID.appendChild(newScript);
Wrap your table related code into a function and call it once on document.ready and after you ajax-request. Avoid triggering document.ready as suggested by Uoli, because it can cause unpredictable side effects as all your $(document).ready(function() { blocks will be executed again.

Categories

Resources