最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Execute function onload only first time - Stack Overflow

matteradmin8PV0评论

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=".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>

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./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!

Share Improve this question edited Nov 2, 2016 at 19:18 buczek 2,0507 gold badges29 silver badges42 bronze badges asked Nov 2, 2016 at 18:15 Alexander PulidoAlexander Pulido 1241 silver badge10 bronze badges 3
  • I think what you are looking for is a log in feature. – David Gomez Commented Nov 2, 2016 at 18:18
  • Why are you using javascript to do something CSS can do for you? Granted, it will need to have something server-side to check whether or not to display the menu or not, but yeah... using javascript to show/hide menu items is bad design, and should be avoided. – junkfoodjunkie Commented Nov 2, 2016 at 18:20
  • it's not, if i do with css only, then everytime the page is loaded, the css will apply, the idea of doing with javascript if to control when to do it. – Alexander Pulido Commented Nov 2, 2016 at 18:32
Add a ment  | 

3 Answers 3

Reset to default 2

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

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

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=/";      
});
Post a comment

comment list (0)

  1. No comments so far