Alexander Pulido
Alexander Pulido

Reputation: 124

Execute function onload only first time

I have a menu in the header with the following structure

$(document).ready(function(){
	$('.dropdown').on('show.bs.dropdown', function(e){
		$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
	});
    $('.dropdown').on('hide.bs.dropdown', function(e){
    	$(this).find('.dropdown-menu').first().stop(true, true).slideUp();
  	});

	$('#entrar').click(function(e){
	    $('#head').slideToggle();
    	$(".boton").css("display","none");
    	$("#secciones").slideToggle();
        $("#foot").slideToggle();
	});
    $('#entrar').click(function() {
     $('html, body').animate({
        scrollTop: $(".principal").offset().top + 70
     }, 700);
    });
});

$(document).ready(init);
	function init(){
    var sec = document.getElementById("secciones");
    var he = document.getElementById("head");
    var fo = document.getElementById("foot");
    he.style.display = "none";
    sec.style.display = "none";
    fo.style.display = "none";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div class="main_wrapper">
    <header id="head">
		<div class="container">
			<section class="row">
				<article class="col-xs-3">
					<h1 id="main_logo">
						<a href="index.php"><img src="images/logo.png" alt=""></a>
					</h1>
				</article>
				<article class="col-xs-9">
					<ul class="nav nav-pills" id="menu">
						<li class="active"><a href="index.php">INICIO</a></li>
						<li class="dropdown">
							<a class="dropdown-toggle" data-toggle="dropdown" href="#">MODELOS<span class="caret"></span></a>
							<ul class="dropdown-menu">
								<li><a class="sec_index" href="index.php#galeria">Modelos en Panamá</a></li>
							</ul>
						</li>
						<li class="dropdown">
							<a class="dropdown-toggle" data-toggle="dropdown" href="#">BLOG<span class="caret"></span></a>
							<ul class="dropdown-menu">
								<li><a class="sec_index" href="index.php#blog">Últimas Entradas</a></li>
								<li><a href="blog.php">Blog Chicas507</a></li>
								<li><a href="glosario.php">Glosario de Términos</a></li>
							</ul>
						</li>
						<li class="dropdown">
							<a class="dropdown-toggle" data-toggle="dropdown" href="#">ANÚNCIATE<span class="caret"></span></a>
							<ul class="dropdown-menu">
								<li><a class="sec_index" href="index.php#paquetes">Paquetes</a></li>
								<li><a href="registro.php">Regístrate</a></li>
								<li><a href="recuperar.php">Recuperar Cuenta</a></li>
							</ul>
						</li>
						<li><a class="sec_index" href="index.php#contacto">CONTACTO</a></li>
						<li><a href="about.php">INFORMACIÓN</a></li>
						<li><a href="login.php">INGRESA</a></li>
					</ul>
				</article>
			</section>
		</div>
	</header>
    <section class="principal" id="principal">
			<div class="boton" id="entrar"><a href="#">ENTRAR</a></div>
			<div class="boton" id="salir"><a href="#">SALIR</a></div>
		</section>
	<section class="secciones" id="secciones">
      some sections
    </section>
    <footer id="foot">
    </footer>
  </div>
</body>

And I have various sections in the webpage, some of the links from the menu gets me to the section in the index, for example index#models. Everything works fine, but here's the thing. I have some JavaScript code that hides the sections and the header called init. I use onload in the body to call the function and a button "entrar" to display. This works, but the function is called everytime I reload the page and I want to just run the first time and when the page is refreshed. Everything is showing without clicking the button. Also, I don't want to load when I change to another part of the site. For example, if I enter the blog and then I click to go home, the function loads and I have to click "entrar" again. I don't want that.

I have been trying to fix this, but I can't find the solution. I appreciate your help. Please!

Upvotes: 1

Views: 7940

Answers (3)

Asons
Asons

Reputation: 87191

I would go with a cookie, which is meant to store a small value, where you simply check for its existence.

Combined with CSS and you get a small and efficient solution.

With the below CSS/JS, when the page loads first time it creates the cookie, the second time add the loadedonce to the html element, and then the CSS kicks in, showing the hidden elements

By simply move the creation of cookie to the button click, it will show them only after that button been clicked.

Since cookies won't work in Stack snippets, I made a fiddle demo with your code

CSS

#secciones, #head, #foot, .loadedonce .boton {
  display: none;
}
.loadedonce #secciones, .loadedonce #head, .loadedonce #foot {
  display: block;
}

JS if on load (either in the head or in the beginning of your js file)

(function(d) {
  if (document.cookie.indexOf("loadedonce=yes") < 0) {
    document.cookie = "loadedonce=yes; expires=Thu, 31 Dec 2099 12:00:00 UTC; path=/";      
  } else {
    d.classList.add('loadedonce');    
  }
})(document.documentElement);

JS if on click

(function(d) {
  if (document.cookie.indexOf("loadedonce=yes") >= 0) {
    d.classList.add('loadedonce');    
  }
})(document.documentElement);


$('#entrar').click(function() {
    document.cookie = "loadedonce=yes; expires=Thu, 31 Dec 2099 12:00:00 UTC; path=/";      
});

Upvotes: 0

OK sure
OK sure

Reputation: 2646

You can set a localStorage var if you want it to persist after the browser closes:

$(function() {
    var visited = localStorage['visited'];
    if (!visited) {
       init();
       localStorage['visited'] = true;
    }

    function init() {
        var sec = document.getElementById("secciones");
        var he = document.getElementById("head");
        var fo = document.getElementById("foot");
        he.style.display = "none";
        sec.style.display = "none";
        fo.style.display = "none";
    }
});

Or sessionStorage if you want it to happen after the browser gets closed:

$(function() {
    var visited = sessionStorage['visited'];
    if (!visited) {
       init();
       sessionStorage['visited'] = true;
    }

    function init() {
        var sec = document.getElementById("secciones");
        var he = document.getElementById("head");
        var fo = document.getElementById("foot");
        he.style.display = "none";
        sec.style.display = "none";
        fo.style.display = "none";
    }
});

Upvotes: 1

Nandan Bhat
Nandan Bhat

Reputation: 1563

You can make use of HTML5 webstorage.

    if (typeof(Storage) !== "undefined")
    {
        console.log("Your browser doesn't support webstorage");
    } 
    else if (sessionStorage.getItem("ui_flag") === null) // Check if the key is set. It's a self defined key.
    {
        sessionStorage.setItem("ui_flag", 1); // If not set, set it
        $(document).ready(init); // Now call your init function here. This code will execute only once for a window.
    }
    else
    {
        //No Action. It's not the first time.
    }

Upvotes: 2

Related Questions