SporeDev
SporeDev

Reputation: 608

Darken screen when clicking on a link then redirect

I have the following project.

What I want is, when a user clicks on any link on the page, to slowly hide the image with the class map and smoothly display the black background, then return to its usual behaviour, redirecting the user to the next page.

My guess is that preventDefault() is the solution here together with some CSS like this one:

.hideImg{ 
 opacity: 0; 
 visibility: hidden;
 -webkit-transition: visibility 0.3s linear,
 opacity 0.3s linear;
 -moz-transition: visibility 0.3s linear,
 opacity 0.3s linear;
 -o-transition: visibility 0.3s linear,
 opacity 0.3s linear; 
}

body{
background-color:#000;
}

However, I fail to make them work together and create a JS that waits for the hiding animation to occur and then redirect.

How can I achieve this?

Upvotes: 2

Views: 184

Answers (3)

Alex Mulchinock
Alex Mulchinock

Reputation: 2269

Try something like this:

$('a').on('click', function(e) {
  e.preventDefault();
  var href = $(this).attr('href');
  
  // For one item
  $('.map').animate({"opacity": "0"}, 1000, function() {
    window.location.href = href;
  });
  
  // Or, for multiple classes - all doing the same thing
  $('.map, .another-item, .another-class').animate({"opacity": "0"}, 1000, function() {
    window.location.href = href;
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="http://www.google.com">Google</a>

<div class='map' style="background: black; width: 300px; height: 300px;"></div>

Upvotes: 2

Farbod Ghasemi
Farbod Ghasemi

Reputation: 97

I think this should do the work for you using jQuery:

$('a').on('click',function(e){
    e.preventDefault;
    $(this).addClass('hideImage');
    $('.hideImage').on('animationend webkitAnimationEnd',function(){
        window.location.href = $(this).attr('href');
    })
});

or just give you the idea of how to fix it.
best of luck

Upvotes: 1

Kumar
Kumar

Reputation: 3126

You can add a class to the container that's holding the image. And add an additional timeout before you go the new page.

$(".x").on('click', function(e) {
  e.preventDefault();
  $('div').addClass('darken');

  window.setTimeout(function() {
    window.location.href = 'https://www.google.com'; // this will navigate to the new page after 2s
  }, 2000);

});
body {
  background: black;
}

.warpper-map {
  width: 500px;
  height: 200px;
}

img.map {
  width: 100%;
  height: 100%;
}

.darken {
  opacity: 0;
  transition: opacity 2s ease; /* Makes smooth transition */
  /* You can increase the time to make the transition much longer */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a class='x' href="#">Click to Darken</a>
<div class='wrapper-map'>
  <img class='map' src="https://sporedev.ro/pleiade/images/Lobby.jpg">
</div>

Upvotes: 2

Related Questions