How to prevent iframe load event? - javascript

I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).
Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.
Thanks

mmm you said you're on aspx page,
I suppose that the iframe do a postback, so for this it reload the page.
If you can't avoid the postback, you've to set a flag on the main page just before posting back, and check against that while you're loading...
...something like:
mainpage.waitTillPostBack = true
YourFunctionCausingPostBack();
..
onload=function(){
if(!mainpage.waitTillPostBack){
hideTables();
}
mainpage.waitTillPostBack = false;
}

I am not sure what your problem is, but perhaps your approach should be a little different. Try putting code into the iframe what would call functions of the parent. These functions would display the proper table:
<!-- in the main page --->
function showTable1() {}
<!-- in the iframe -->
window.onload = function () {
parent.showTable1();
}
This would put a lot of control into your iframe, away from the main page.

I don't have enough specifics from your question to determine if the iframe second load can be prevented. But I would suggest using a javascript variable to check if the iframe is being loaded a second time and in that case skip the logic for hiding the tables,

This is my code
function initUpload()
{
//alert("IFrame loads");
_divFrame = document.getElementById('divFrame');
_divUploadMessage = document.getElementById('divUploadMessage');
_divUploadProgress = document.getElementById('divUploadProgress');
_ifrFile = document.getElementById('ifrFile');
_tbRetry = document.getElementById('tbRetry');
_tbNext=document.getElementById('tblNext');
_tbRetry.style.display='none';
_tbNext.style.display='none';
var btnUpload = _ifrFile.contentWindow.document.getElementById('btnUpload');
btnUpload.onclick = function(event)
{
var myFile = _ifrFile.contentWindow.document.getElementById('myFile');
//Baisic validation
_divUploadMessage.style.display = 'none';
if (myFile.value.length == 0)
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Please select a file.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
var regExp = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.doc|.txt|.xls|.docx |.xlsx)$/;
if (!regExp.test(myFile.value)) //Somehow the expression does not work in Opera
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Invalid file type. Only supports doc, txt, xls.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
_ifrFile.contentWindow.document.getElementById('Upload').submit();
_divFrame.style.display = 'none';
}
}
function UploadComplete(message, isError)
{
alert(message);
//alert(isError);
clearUploadProgress();
if (_UploadProgressTimer)
{
clearTimeout(_UploadProgressTimer);
}
_divUploadProgress.style.display = 'none';
_divUploadMessage.style.display = 'none';
_divFrame.style.display = 'none';
_tbNext.style.display='';
if (message.length)
{
var color = (isError) ? '#008000' : '#ff0000';
_divUploadMessage.innerHTML = '<span style=\"color:' + color + '\;font-weight:bold">' + message + '</span>';
_divUploadMessage.style.display = '';
_tbNext.style.display='';
_tbRetry.style.display='none';
}
}
tblRetry and tblNext are the tables that I want to display depending on the result of the event.

Related

Onload need to work only once

Good day everyone i'm having a trouble about working my onload only once . because when i refreshes the page or if i am going to another page it always load.
here is my code so far:
JS
<!--Auto load the on overlay function-->
<script>
window.onload = function openNav() {
document.getElementById("myNav").style.width = "100%";
splashScreen();
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
</script>
and here's my js functionality for my splashscreen.js
//use onload when in your html the context is not inside
//the <header>
//create a splashScreen function
function splashScreen(){
//get the element on the html side with the id of "skip"
var skipButton = document.getElementById("skip");
//counter for the countdown
var counter = 5;
//create an element <p>
var newElement = document.createElement("p");
newElement.innerHTML = "Skip this 5 seconds";
var id;
skipButton.parentNode.replaceChild(newElement, skipButton);
id = setInterval(function(){
counter--;
if(counter < 0){
//replace the newElement on else condition statement
newElement.parentNode.replaceChild(skipButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = "You can skip this in " + counter.toString() + " seconds.";
}
}, 1000);
}
and this is how i call it on my html
<html>
<body>
<!--SplashScreen JS-->
<script src="<?php echo base_url('assets/public/js/splashscreen.js');?>">
</script>
When you refresh the page or go to another page, then back to your original page, the page is reloading, thus the onLoad handler is being called.
If you want certain functionality to only happen once, then one thing you can try is setting a cookie that you can check on page load. If the cookie is set, you know you already loaded it once, and don't run the code again. If not, you run the code, then set the cookie.
Useful link for cookies:
https://www.w3schools.com/js/js_cookies.asp
To be able to know that the splash screen has already been displayed for a given user, you need to store something to that effect that persists between page load events. Since the page will reload when the refresh button is clicked or when coming back to the page after being there earlier, this stored item can't be in the page itself, because it will just get reinitialized every time the page loads.
Cookies (as mentioned in another answer) are an option, but localStorage, I think is much simpler. It works like this:
// Once the window is loaded...
window.addEventListener("load", function(){
// Check localStorage to see if the splash screen
// has NOT already been displayed
if(!localStorage.getItem("splash")){
// Splash has not been displayed, so show it:
splashScreen();
// Store a value in localStorage to denote that the splash screen
// has now been displayed
localStorage.setItem("splash", "true");
}
});
One approach is to set .name property of window, which remains set after window.
const NAME = "once";
window.onload = function openNav() {
document.getElementById("myNav").style.width = "100%";
if (this.name !== NAME) {
this.name = NAME;
splashScreen();
} else {
// do other stuff
console.log(this.name)
}
}

Replacing iframe source with Javascript - Can I use a loop?

I have a list of items (districts) on a page, and an iframe pulling in a map on the same page. When a user clicks on one of the districts, the JavaScript changes the source of the iframe to show a map of the district the user clicked.
My current code simply uses an "onclick" for each district, which then calls a function to change the source of the iframe.
I am wondering if I can simplify this code at all, possibly by using a loop? If I have 15 more districts to add to the page, will I have to add another "onclick" and another function for each one? Or is there an easier way that I am missing?
Simplified HTML:
<div id="districtlist">
Allen
Barren
Butler
<!--about 15 more links to follow-->
</div>
<iframe id="maparea" src="http://www.reddit.com"></iframe>
Javascript:
var a = document.getElementById("districtlist")
a.getElementsByTagName("a")[0].onclick = Allen;
a.getElementsByTagName("a")[1].onclick = Barren;
a.getElementsByTagName("a")[1].onclick = Butler;
//more lines...
function Allen() {
document.getElementById("maparea").src="http://www.youtube.com";
}
function Barren() {
document.getElementById("maparea").src="http://www.mentalfloss.com";
}
function Butler() {
document.getElementById("maparea").src="http://www.amazon.com";
}
//more functions...
I believe you could try this
var elems = document.getElementById("districtlist").querySelectorAll('a');
[].forEach.call(elems, function(elem) {
elem.onclick = function() {
var url = '';
switch(elem.innerText) {
case 'Allen':
url = "http://www.mentalfloss.com";
break;
case 'Barren':
url = "http://www.mentalfloss.com"
break;
case 'Butler':
url = "http://www.amazon.com";
break;
}
document.getElementById("maparea").src=url;
}
});

reload div javascript only ajax needed?

please refer to JSFiddle link: https://jsfiddle.net/s11oo2gg/.
We are not allowed to use jQuery and iframe here.
The problem right now if you click on resistor first and hover over different content images then come back out by clicking the X mark, the content image would get stucked where you left off and would not load the the other content images properly. It would show a broken image link.
I like to reload only the <div id="slider1_contain"> everytime I click on <span class="closeButton">(X mark) so the target content images can be loaded accordingly.
I dont not want to have location.reload(); to resolve this when the X is click. I dont want to reload the whole page but only the div.
I saw people were asking the same question and solve it with AJAX. Do I need AJAX for this case? Or is there something we can do in the following javascript?
Thank you in advance!!
<script type="text/javascript">
function showContent(target){
document.getElementById(target).style.display = 'block';
document.getElementById("boxThumb").style.display = 'none';
}
function hideContent(target){
document.getElementById(target).style.display = 'none';
document.getElementById("boxThumb").style.display = 'block'
}
</script>
<script type="text/javascript">
var children = document.querySelectorAll('.toggle > section[id]');
function showDetailContent(target) {
// Simply loop over our children and ensure they are hidden:
for (var i = 0, child; child = children[i]; i++) {
child.style.display = 'none';
}
// Now, show our child we want to show
document.getElementById(target).style.display = 'block';
}
</script>
If you want to reload just the div, you can use innerHTML.
document.getElementById(target).innerHTML = '<img src="image.jpg">';

Javascript to build mvc actionlink conditionally

This is in a VB.NET MVC 3 Razor view and fires when a JsonResult of success is returned. The problem is that I would like to conditionally build an actionlink if data.Object.Status == 'Completed';
I have looked around and nothing seems to be fitting at all to solve this. This is what the actionlink should look like in razor:
#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = currentItem.firstName, .lastname = currentItem.lastName, .classRef = currentItem.course_ref, .cNumber = currentItem.conf_number}, Nothing)
And this is the javascript function that will do it. Currently it just Places the contents of data.Object.Status. Which should only show like that when data.Object.Status != 'Completed';
function updateSuccess(data) {
if (data.Success == true) {
//we update the table's info
var parent = linkObj.closest("tr");
parent.find(".CompletedClass").html(data.Object.Status);
//now we can close the dialog
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Update Complete");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").html(data.ErrorMessage);
$("#update-message").show();
}
}
Below is what I am thinking will work I am still trying to figure it out but this is a rough markup of it.
function updateSuccess(data) {
if (data.Success == true) {
//we update the table's info
var parent = linkObj.closest("tr");
var d = parent.find(".CompletedClass");
if (data.Object.Status == 'Completed') {
d.html = #Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = Model(0).firstName, .lastname = Model(0).lastName, .classRef = Model(0).Completed_Class, .cNumber = Model(0).conf_number}, Nothing)
}
//now we can close the dialog
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Update Complete");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").html(data.ErrorMessage);
$("#update-message").show();
}
}
What you suggest right now should work, there is a typo on your code assigning the HTML, you probably know it but the way you add HTML to an element is (You have a = sign which is not valid) :
d.html (#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", ....)
Assuming is an element that accepts html, otherwise, use the "text" function.
In any case, my recommendation would be to generate the HTML before hand but have it hidden on the page (unless you have thousands of them, of there are security concerns). Then you just have your Javascript simply show the element:
var parent = linkObj.closest("tr");
var linkElement = parent.find(".mylinkelement-class");
if (data.Object.Status == 'Completed') {
linkElement.show();
}
This should give you the benefit of allowing better separation between your Javascript and your MVC code.
HTH,
-Covo
You should update your code to something like this
d.html('#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = Model(0).firstName, .lastname = Model(0).lastName, .classRef = Model(0).Completed_Class, .cNumber = Model(0).conf_number}, Nothing)');
To assign html with jQuery you should use jQuery.html().
The Razor #Html.ActionLink will print HTML to the page, to not break your Javascript, put those inside quotes d.html('#Html...')

I need to set display: block on div then find an anchor within that div

I'm nearly finished with this project but I have been beating my head against this problem for a day or so.
Big picture:
Im trying to create a link that will jump between tabs and find an anchor.
Details:
I need to create a link which triggers the function that hides the current div (using display: none)/shows another div (display: block;) and then goto an anchor on the page.
My first intuition was to do:
code:
<a onClick="return toggleTab(6,6);" href="#{anchor_tab_link_name}">{anchor_tab_link_name}</a>
Since the onClick should return true and then execute the anchor. However it loads but never goes to the anchor.
Here is the toggleTab function to give some context:
function toggleTab(num,numelems, anchor, opennum,animate) {
if ($('tabContent'+num).style.display == 'none'){
for (var i=1;i<=numelems;i++){
if ((opennum == null) || (opennum != i)){
var temph = 'tabHeader'+i;
var h = $(temph);
if (!h){
var h = $('tabHeaderActive');
h.id = temph;
}
var tempc = 'tabContent'+i;
var c = $(tempc);
if(c.style.display != 'none'){
if (animate || typeof animate == 'undefined')
Effect.toggle(tempc,'appear',{duration:0.4, queue:{scope:'menus', limit: 3}});
else
toggleDisp(tempc);
}
}
}
var h = $('tabHeader'+num);
if (h)
h.id = 'tabHeaderActive';
h.blur();
var c = $('tabContent'+num);
c.style.marginTop = '2px';
if (animate || typeof animate == 'undefined'){
Effect.toggle('tabContent'+num,'appear',{duration:0.4, queue:{scope:'menus', position:'end', limit: 3}});
}else{
toggleDisp('tabContent'+num);
}
}
}
So I posted this on a coding forum and a person told me that my tab code was done in prototype.
And that I should "Long story short: don't use onclick. Attach the data to the A tag and handle the click event yourself (using preventDefault() or similar) to do your tab-setting stuff, then when it's done, manually set your location to the hash tag."
I do understand what he is suggesting but I don't know how to implement it because I don't know much about javascript syntax.
If you can provide any hints or suggestions it would be amazing.
Update:
I tried to implement the solution below like this:
The link:
<a id="trap">trap</a>
Then adding the following js to the top of the page:
<script type="javascript">
document.getElementById("trap").click(function() { // bind click event to link
tabToggle(6,6);
var anchor = $(this).attr('href');
//setTimeout(infoSupport.gotoAnchor,600, anchor);
jumpToAnchor();
return false;
});
//Simple jump to anchor point
function jumpToAnchor(){
location.href = location.href+"#trap";
}
//Nice little jQuery scroll to id of any element
function scollToId(id){
window.scrollTo(0,$("#"+id).offset().top);
}
</script>
But unfortunately it simply doesn't seem to work for me. When I click the text simply nothing happens.
Anyone notice any apparent mistakes? I'm not used of working with javascript.
I found a lot simpler solution:
$(function(){
jumpToTarget('spot_to_go'); //This is what you put inside your function when the link is clicked.
function jumpToTarget(target){
var target_offset = $("#"+target).offset();
var target_top = target_offset.top;
$('html, body').animate({scrollTop:target_top}, 500);
}
});
Working demo:
http://jsbin.com/ivure/3/edit
So on the click event you do something like this:
//Untested
$('#trap').click(function(){
tabToggle(6,6);
var anchor = $(this).attr('href');
jumpToTarget(anchor);
return false;
});
​
Apparently a small delay was all I needed.
I used this for the link. This is preferred for my situation since I'm batch generating many of these links.
trap
Then I used this vanilla javascript
//Simple jump to anchor point
function jumpToAnchor(target){
setTimeout("window.location.hash=target",450);
}
This loads the link and instantly goes to the location. No jerkiness or anything.

Categories

Resources