TDG
TDG

Reputation: 1302

Block fadeout when mouse over or click event on div

I used below code to fade-out #widget in 10 secs and fade-in #floating_widget in 10.2secs. This works fine.

But, #widget container should not fade-out when i clicked or mouseover #widget container. Now, it fade-out automatically because of setTimeout code.

Please let me know how to fix this issue? Thanks

HTML:

<div id="widget">
  <h1>Hello World!</h1>
</div>

<div id="floating_widget">
  <h2>Hello World 2!</h2>
</div>

JS:

setTimeout(function() {
    $('#widget').fadeOut('slow');
}, 10000);
setTimeout(function() {
    $('#floating_widget').fadeIn('slow');
}, 10200);
$('#floating_widget').click(function(){
    $(this).hide();
    $('#widget').show();
});

Upvotes: 1

Views: 53

Answers (1)

P. Hi&#233;ronymus
P. Hi&#233;ronymus

Reputation: 28

I hope I got the right understanding of your question. It seems that you have a problem with the timeouts. You will have to clear them in a onmouseover function. Here is an example of the JavaScript:

var $widget = $('#widget')
var $floatingWidget = $('#floating_widget')

var widgetFadeTimeout = setTimeout(function() {
  $widget.fadeOut('slow')
}, 10000)
var floatingWidgetFadeTimeout = setTimeout(function() {
  $floatingWidget.fadeIn('slow')
}, 10200)

$widget.mouseover(function() { // https://api.jquery.com/mouseover
  // Remove the timeout to avoid triggering the fadeOut and fadeIn
  clearTimeout(widgetFadeTimeout) // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout
  clearTimeout(floatingWidgetFadeTimeout)
  // In case the element began the transitions stop them
  $widget.stop()
  $floatingWidget.stop()
  $floatingWidget.hide()
  $widget.show()
})

$floatingWidget.click(function() {
  $(this).hide()
  $widget.show()
})

I hope this will be useful for you!

Upvotes: 1

Related Questions