Onload need to work only once - javascript

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)
}
}

Related

how to hide django message after it is displayed for few seconds

For example, before redirect, I used
messages.add_message(request, messages.INFO, 'You have successfully updated your listing.')
Then the message will be automatically displayed after redirection, however the message will never disappear, may I know how to hide it after few seconds?
Thanks!!!
You need to write javascript code, use window setTimeout() method to hide message after some time.
// suppose the `id` attribute of element is `message_container`.
var message_ele = document.getElementById("message_container");
setTimeout(function(){
message_ele.style.display = "none";
}, 3000);
// Timeout is 3 sec, you can change it
Put this code inside base.html at the bottom inside <script> tag, so whenever page reloaded after 3
sec it will make your message disappear.
the script:
<script>
setTimeout(function(){
if ($('#msg').length > 0) {
$('#msg').remove();
}
}, 2000) // 2000 millisecond
</script>
the template:
<div id="msg">
{{message}}
</div>
To hide only messages with a certain tag (e.g only INFO messages) you can use the following code inside your HTML document.
<script>
// Get all info messages
var info_messages = document.getElementsByClassName('alert-info');
setTimeout(function(){
for (var i = 0; i < info_messages.length; i ++) {
// Set display attribute as !important, neccessary when using bootstrap
info_messages[i].setAttribute('style', 'display:none !important');
}
}, 3000);
</script>
This one is working fine for me:
var message_ele = document.getElementById("msg");
setTimeout(function() {
message_ele.style.display = "none";
}, 3000);
<span id="msg">
{{messages}}
</span>

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">';

My javascript popup shows for a split second if there's a cookie

I have no clue what I'm doing wrong. It works it just shows the popup for a split second. Would a timeout option be better? Which part is the problem? I'm a little new to Javascript so I don't really know what to exactly look for.
<script language="javascript" type="text/javascript">
/** Create a html cookie and set expiry as a day. **/
function createCookie(name,value,days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = date.toGMTString();
document.cookie = name+"="+value+"; expires="+expires+"; path=/";
}
/** Check if already a cookie has been created. **/
function readCookie(name) {
var flag = 0;
var dcmntCookie = document.cookie.split(';');
for(var i=0;i < dcmntCookie.length;i++) {
var ck = dcmntCookie[i];
while (ck.charAt(0)==' ') {
ck = ck.substring(1,ck.length);
}
if(ck) {
cparts = ck.split('=');
if (cparts[0] == name) flag=1;
}
}
if(flag) {
return true;
} else {
return false;
}
}
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
document.getElementById('google').style.display = "none";
document.getElementById('google').style.visibility = "hidden";
}
else createCookie(name,"cookie 4 the day",1);
}
</script>
<script type="text/javascript">
function closeThisDiv()
{
var openDiv = document.getElementById('google');
openDiv.style.display = 'none';
}
</script>
<body onLoad="checkCookie('MyCookie')"
If your goal is to have the element with id="google" to be hidden from the very beginning of the page display (so it never shows), then you should add a CSS rule that loads in the head section like this:
#google {display: none;}
Or, you should add a style element to the HTML itself:
<div id="google" style="display:none"></div>
As your code is currently written, it sounds like it is doing what it is supposed to. It waits for the entire document to be loaded (including images) and then it hides the element with id="google". That means the item will show briefly while the page is loading and then your code will hide it.
If you can't modify the CSS or the HTML for the google object and you're just trying to hide it as soon as possible with javascript and the google object is present in the HTML of your page (not added programmatically), then you can do this:
<body>
other HTML here
<script>
// script that executes right before the /body tag
checkCookie("MyCookie")
</script>
</body>
This will at least not wait for all images to load before hiding it.
I fixed it like this:
Create a css property of display:none; for #google
#google{display:none;}
Then switch around the last portion of code to display only if they don't have the cookie, and to create the cookie.
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
if (readCookie(name)) {
}
else document.getElementById('google').style.display = "inline";
document.getElementById('google').style.visibility = "visibility";
createCookie(name,"cookie 4 the day",1);
In case anyone runs into this problem. Worked great for me.

Splash Page Video (jQuery Hide) Reveal Index Underneath Issue

I need to have a splash page, but I don't want to make it my index, so I am using this solution.
I am using this technique:
http://jsfiddle.net/JjvzT/
on this page:
http://www.kineticoriginsofrhythm.com/
But I cant get the "Enter" button to reveal the index page below. Any Suggestions? It just flickers and jumps back to the Video Splash Page.
Also whats the js cookie code that makes it only appear once per day?
Thank You Very Much.
Also, if you can save your "anti-Splash" debates for another time that would be great. Client "MUST HAVE" this splash page. Not my idea.
Change the href attribute for your "Enter" anchor to "#". Right now you are redirecting them to the same page after hiding the splash, which is forcing them to load the page in its initial state again.
EDIT: For the cookie,
jQuery(function(){
if(document.cookie.indexOf("firstvisit") != -1){
$("#splash").hide();
$("#container-index").show();
}
else{
$("#splash span").click(function() {
$("#splash").hide();
$("#container-index").show();
var expireDate = new Date();
/* sets expire date to current date + 1 day */
expireDate.setDate(expireDate.getDate() + 1);
var newCookie = "firstvisit=0;expires=" + expireDate.toUTCString();
document.cookie = newCookie;
});
}
});
Caveat: I haven't tested this. See here for more on JavaScript and cookies: http://www.w3schools.com/JS/js_cookies.asp
I took ZDYN's answer and created splash.js, which can simply be added to your splash page (not a hidden div) and to the page that you want to redirect from, ie. index.html or something.
Anyway, here's the commented, working code:
/*
1. Create a separate html page to be the splash page
2. Out a referrence to this script in the splash page
-put below the "jquery.js" script reference
<script type="text/javascript" src="Scripts/splash.js"></script>
3. Put a reference to this script in every page that you want to have the splash page appear on
-put below the "jquery.js" script reference
<script type="text/javascript" src="Scripts/splash.js"></script>
4. Set the "splashPageName" below to the file name of the splash page
5. Set the date variables below
*/
var splashPageName = "splash.html";
var endSplashDate = new Date("12/7/2011");
var expireCookieDate = new Date();
(function() {
var url = window.location.toString();
if (url.toLowerCase().indexOf(splashPageName) >= 0) {
/* sets expire date to date + 1 day */
expireCookieDate.setDate(expireCookieDate.getDate() + 1);
var newCookie = splashPageName + "=0;expires=" + expireCookieDate.toUTCString();
document.cookie = newCookie;
}
else {
if (document.cookie.indexOf(splashPageName) != -1) {
//stay here, they've already seen the splash page
}
else {
var today = new Date();
if (endSplashDate > today) {
window.location = splashPageName;
}
}
}
} ());
Try this
$(document).ready(function(){
$("#splash").click(function() {
$(this).hide();
$("#container-index").show();
});
});

How to prevent iframe load event?

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.

Categories

Resources