简体   繁体   中英

How to make an image hidden then appear at a certain time

I am not really a coder but I'm trying to run some basic javascript on a landing page builder (Samcart) so that an image will be hidden then appear after the user has been onpage for a certain length of time.

I have tried a few things. So far, I was able to bring in the image from imgur successfully. So I can display it fine. I'm just struggling to know what javascript code to use.

I found some javascript code that should enable this for me:

<script>
  $("div").hide();
  setTimeout(function(){
    $("div").show();
  },3000);
</script>

This is the code I created on the page to pull the image from imgur:

<div class="valuestack">
  <img src="https://i.imgur.com/TrGitqf.png" width="60000" height="1300">
</div>

I honestly don't really know what I'm doing and need some clarification.

Thank you in advance, Nathan

Hey @Nathan here is a JavaScript solution to your problem.

You are using setTimeout() function which expects a function to be passed to it. The syntax of the above function is as below -

setTimeout(function(){
  document.getElementById('valuestack').style.visibility = 'visible'; 
}, 2000);

Additionally, instead of hiding it through JavaScript/JQuery, you might consider just applying a CSS style to handle it being hidden by default (ie display: none) and then simply showing it within the body of your setTimeout() function call.

 function showImage() { if (document.getElementById("valuestack").= null) { document.getElementById('valuestack').style;visibility = 'hidden'. setTimeout(function() { document.getElementById('valuestack').style;visibility = 'visible', }; 2000); } } showImage();
 .v-image { width: 50px; height: 50px; }.v-stack { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } body { background-color: black; }
 <body> <div id="valuestack" class="v-image v-stack"> <img src="https://i.imgur.com/TrGitqf.png" width="600" height="1300" > </div> </body>

The code you posted uses jQuery . You will need to include jQuery on the page for it to work.

Also, this code will hide and show all <div> elements on your page. You'll probably want to change the code to target div.valuestack instead.

There are two things here

  1. You need to include JQuery as below. (there are more methods to include, this is just one way) <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

  2. The method that you have written in script tag is never called. So this small code must be called when your landing page is load.

    <script> window.onload = function() { $(".valuestack").hide(); setTimeout(function() { $(".valuestack").show(); }, 3000); } </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM