pHenomen
pHenomen

Reputation: 153

Transfer image into another div on scroll;

Here is my problem:

I have image in one div that is centered into that div. I want that that image go in header after user scroll once (scroll>50).

Here is my codepen example.

HTML:

<header> <div id="nav"> LINK LINK LINK </div> </header>

<div id="main">
  <img src="https://img.clipartfest.com/3c73a51504b9b1ee6d200d1e60725b79_triangle-quilatral-triangle-shape-clipart-no-background_2400-2080.png">
</div>

CSS:

*{
  padding:0;
  margin:0;
  overflow-x:hidden;
}

#nav{float:right; line-height:70px;}

header{
  width:100%;
  position:fixed;
  padding-left:10%;
  padding-right:10%;
  background:#fff;
  height:70px;
}

#main{
  padding-top:100px;
  text-align:center;
  height:800px;
  background:#3cb5f9;}
#main img{width:200px; margin:0 auto;}

Upvotes: 0

Views: 148

Answers (1)

couzzi
couzzi

Reputation: 6366

There are a ton of ways to do this, but a quick way to achieve this is to duplicated the image so there is a copy of it in the main and the header. On load, have it hidden within the nav. Then, have a scroll event listener that watches for an offset of >50.

If true, => hide main image, and show nav image If false => show main image. and hide nav image.

Also worth noting I updated the height of main to be 200vh — just to simulate content. This is not related to the answer.

$(function(){
 
 $(window).bind('scroll', function(){
   
   if($(window).scrollTop() >= 50){
     $("#main img").hide();
     $("header img").show();
   }else{
     $("#main img").show();
     $("header img").hide();
   }
   
 });
  
 
});
* {
  padding: 0;
  margin: 0;
  overflow-x: hidden;
}

#nav {
  float: right;
  line-height: 70px;
}

header {
  width: 100%;
  position: fixed;
  padding-left: 10%;
  padding-right: 10%;
  background: #fff;
  height: 70px;
}

header img {
  display: none;
  width: 50px;
  margin: 0 auto;
}

#main {
  padding-top: 100px;
  text-align: center;
  height: 200vh;
  background: #3cb5f9;
}

#main img {
  width: 200px;
  margin: 0 auto;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title></title>
  <link rel="stylesheet" href="style.css" />
  <script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="script.js"></script>
</head>

<body>

  <header>
    <div id="nav"> LINK LINK LINK </div>
    <img src="https://img.clipartfest.com/3c73a51504b9b1ee6d200d1e60725b79_triangle-quilatral-triangle-shape-clipart-no-background_2400-2080.png">
  </header>

  <div id="main">
    <img src="https://img.clipartfest.com/3c73a51504b9b1ee6d200d1e60725b79_triangle-quilatral-triangle-shape-clipart-no-background_2400-2080.png">
  </div>
</body>

</html>

External Plunker: http://plnkr.co/edit/yS5MdtCeTNJvvn7w5gvl?p=preview

Upvotes: 1

Related Questions