Hide div after being shown - javascript

I have some code that shows a div with a message in it when button is clicked. I want the div to disappear after a few seconds.
I have tried to achieve this adding $(this).delay().hide(500); in the .notify function but it doesn't work.
$.fn.notify = function(settings_overwrite) {
settings = {
placement: "top",
default_class: ".message",
delay: 0
};
$.extend(settings, settings_overwrite);
$(settings.default_class).each(function() { $(this).hide(); });
$(this).show().css(settings.placement, -$(this).outerHeight());
obj = $(this);
if (settings.placement == "bottom") {
setTimeout(function() { obj.animate({ bottom: "0" }, 500) }, settings.delay);
}
else {
setTimeout(function() { obj.animate({ top: "0" }, 500) }, settings.delay);
}
}
/** begin notification alerts
-------------------------------------**/
$(document).ready(function($) {
$('.message').on('click', (function() {
$(this).fadeTo('slow', 0, function() {
$(this).slideUp("slow", function() {
$(this).remove();
});
});
}));
});
$(document).ready(function() {
if (document.location.href.indexOf('#notify_success') > -1) {
$("#notify_autopop").notify({
delay: 500
});
}
});

You can use setTimeout function
You have to store the divobj in a variable and then use it inside the setTimeout function
$('div').click(function(){
//show the message
var divObj = $(this);
setTimeout(function(){
divObj.hide();
},3000);
});
check the fiddle link
https://jsfiddle.net/uujf8hmq/

You can write your code to hide the div in the 2nd argument of show() methos which is a complete callback. You need to hide() the element in this callback. You can put necessary timeout before hide().

You can use CSS3 animation/transition instead of jquery's animation. and you can use setTimeout to fade message after sometime.
See the below code
JS
$.fn.notify = function(message, settings_overwrite){
var settings = {
placement:"top-left",
delay: 2000
};
$.extend(settings, settings_overwrite);
var $this = $(this);
$this.removeClass('bottom-left top-left');
$this.text(message);
$this.addClass(settings.placement + ' display');
$this.on('click', function(){
$this.removeClass('display');
});
setTimeout(function(){
$this.removeClass('display');
}, settings.delay);
}
$(document).ready(function ($) {
$('body').on('click', '.create-message', function(){
$('.message').notify($('#msg').val(), {
placement: $('#pos').val()
});
});
});
HTML
Position :
<select id="pos">
<option value="top-left" selected>Top Left</option>
<option value="bottom-left">Bottom Left</option>
</select>
<br/>
<textarea id="msg"></textarea>
<br/>
<button class="create-message">show message</button>
<div class="message"></div>
CSS
.message{
position: fixed;
width: 100px;
height: 50px;
background: green;
color: white;
padding: 3px;
border-radius: 3px;
opacity: 0;
-webkit-transition: opacity 1s;
transition: opacity 1s;
}
.message.display {
opacity: 1;
}
.message.top-left {
top: 10px;
right: 10px;
}
.message.bottom-left {
bottom: 10px;
right: 10px;
}
jsfiddle link - http://jsfiddle.net/jigardafda/ac5wyfo9/3/

Usually we do not use $(document).ready(function() {....}(); twice on a single page.
Try writing code to hide the div inside the same $(document).ready(function() {.....}() after the .show() function.
You can use either .hide() or setTimeout() functions to hide the div.

Related

How can I hide this setting-box on a click on the gear icon and anywhere outside of the body?

this the CSS I use.
.setting-box
{
position: fixed;
left:-200px;
top:0;
width: 200px;
z-index: 1000;
min-height: 100vh;
}
.toggle-setting
{
position: absolute;
right: -34px;
top: 6em;
background: #fff;
border-radius: 0px 5px 5px 0;
text-align: center;
cursor: pointer;
}
I tried a lot of things but it doesn't work!
that code works very well but.
except when I click on the page the setting box doesn't close
$('.setting-box .toggle-setting').on('click',function () {
$(this).parent('.setting-box').toggleClass('open');
if ($(this).parent('.setting-box').hasClass('open')) {
$(this).parent('.setting-box').animate({
left:0,
},1000);
} else {
$(this, 'body').parent('.setting-box').animate({
left:'-200'
},1000);
}
});
You can try this.
EDIT
var clicked = false;
$('.setting-box .toggle-setting').on('click',function () {
if (clicked == false) {
$(this).parent('.setting-box').animate({
'left' : '0',
},1000);
clicked = true;
} else {
$(this).parent('.setting-box').animate({
'left' : '-200px',
},1000);
clicked = false;
}
console.log(clicked);
});
$(document).click( function () {
var target = $(event.target);
if (!target.is(".toggle-setting") && !target.is('.setting-box') && clicked == true) {
$('.setting-box').animate({
'left' :'-200px',
},1000);
clicked = false;
console.log(clicked);
}
});
the first function do toggle setting box;
$('#gear-button').click(function() {
$(".setting-box").toggleClass("display-block");
});
second function hide setting box on document click (body click)
// hide setting box on body click
$(document).on('click', function() {
$(".setting-box").removeClass("display-block");
});
the third function stop the click event when the user clicks on a button or setting box to prevent document click
$("#gear-button, .setting-box").click(function(e) {
e.stopPropagation();
})
In general, you can use this template to add your own animation and classes.
the full example :
JSFiddle
You can place the settings block in another block, place the settings in the align:center;,
add from this from the z-index:; and make when you click on the gear, or anywhere, so that this block takes the style of display:none;. This may help you.

How to fire event after 3 sec of hovering

I have a div and I want to fire an event only after user continuous hovers his mouse for 3 sec. My code doesn't work well because it fires right after hover and doesn't "wait".
Code:
$(".inner_pic").mouseenter(function () {
setTimeout(function () {
alert('testing');
}, 3000);
}).mouseleave(function () {
alert('finish');
});
You need to store timeout id somewhere and clear it on mouseout. It's convenient to use data property to save this id:
$(".inner_pic").mouseenter(function () {
$(this).data('timeout', setTimeout(function () {
alert('testing');
}, 3000));
}).mouseleave(function () {
clearTimeout($(this).data('timeout'));
alert('finish');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner_pic">PICTURE</div>
You can achieve this by delay option:
Working demo
$('#elem').popover({
trigger: "hover",
delay: {show : 3000, hide : 0} });
Checkout the below code
var myVar;
$( "div#container" )
.mouseover(function() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
})
.mouseout(function() {
clearTimeout(myVar);
});
div {
background: red;
margin: 20px;
height: 100px;
width: 100px;
display:block;
cursor: pointer;
}
div:hover {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
var st;
$(".inner_pic").mouseenter(function(e) {
var that = this;
st = setTimeout(function() {
alert('testing');
}, 3000);
}).mouseleave(function() {
clearTimeout( st );
alert('finish');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner_pic">
<h3>Picture Here - Hover me</h3>
</div>
Assuming you have a div with id of myelement, you can do this:
var divMouseOver;
$('#myelement').mouseover(function() {
divMouseOver = setTimeout(function() {
alert("3 seconds!"); //change this to your action
}, 3000);
});
$('#myelement').mouseout(function() {
if (divMouseOver) {
clearTimeout(divMouseOver);
}
});
BTW, tere's a helpful clarifying question re: using mouseenter and mouseover right here: Jquery mouseenter() vs mouseover(). Consider this when choosing which to use.

jQuery slide back when clicked anywhere on the page

$(".links").click(function(){
$('.slider').stop(true,false).animate({ right: "0" }, 800, 'easeOutQuint');
}, function() {
$(".slider").stop(true,false).animate({ right: "-200" }, 800, 'easeInQuint');
}, 1000);
I am building a little slider on my website. The slider position is right: -200. It slides to position right: 0 I want to animate it back to position right: -200 after clicking anywhere else on the page.
I tried all the ways which failed. toggle(slide) works good but doesn't looks good.
http://jsfiddle.net/aofg5v78/
Putting your code through the JavaScript beautifier (it's always good to do it to your code that you post to make it easier to understand) gives this:
$(function () {
$(".links")
.click(function () {
$('.slider')
.stop(true, false)
.animate({
right: "0"
}, 800, 'easeOutQuint');
},
function () {
$(".slider")
.stop(true, false)
.animate({
right: "-200"
}, 800, 'easeInQuint');
}, 1000);
});
You're trying to pass two handlers to .click() and something that looks like a timeout or duration (1000). Try something like this:
$(function () {
var toggle;
$(".links")
.click(function () {
toggle = !toggle;
if (toggle) {
$('.slider')
.stop(true, false)
.animate({
right: "0"
}, 800, 'easeOutQuint');
}
else {
$(".slider")
.stop(true, false)
.animate({
right: "-200"
}, 800, 'easeInQuint');
}
});
});
Update: To make it slide when you click anywhere on the page it's slightly more complicated:
$(function () {
var toggle;
$(document).click(function () {
if (toggle) {
toggle = !toggle;
$(".slider")
.stop(true, false)
.animate({
right: "-200"
}, 800, 'easeInQuint');
}
});
$(".links")
.click(function (e) {
e.stopPropagation();
toggle = !toggle;
if (toggle) {
$('.slider')
.stop(true, false)
.animate({
right: "0"
}, 800, 'easeOutQuint');
}
else {
$(".slider")
.stop(true, false)
.animate({
right: "-200"
}, 800, 'easeInQuint');
}
});
$(".slider")
.click(function (e) {
e.stopPropagation();
});
});
This part:
$(".slider")
.click(function (e) {
e.stopPropagation();
});
is there to not hide the slider when you click on the slider (and not somewhere else on the page, outside of the slider) but if that's not what you want then you can remove it.
(The code could be refactored to remove duplication and to avoid running the selectors multiple times but it serves the purpose of this example. Also, you can't have more than one such slider on a page right now because all will slide at the same time but I guess that's ok.)
See DEMO.
It would be simpler for older jQuery versions with the toggle method but unfortunately it was deprecated in version 1.8 and removed in version 1.9.
(By the way, the easing functions that you are using are not available in plain jQuery by default. They are available if you're using jQuery UI but if you're not then you have to add them before you can use them. Just something to keep in mind to avoid the unhelpful "undefined is not a function" exception.)
Heres a different take:
DEMO
css
.slider {
position: absolute;
top: 200px;
height: 200px;
width: 200px;
background: #000;
/* relevant */
transform: translateX(-200px);
transition: transform 400ms ease-in-out;
}
.slider.shown {
transform: translateX(0);
}
jquery js
$(document).ready(function(){
var $slider = $('.slider').addClass('shown');
$(document).on('click', '*:not(.slider)', function(e) {
//// as described in question in on load, out on click
// $slider.removeClass('shown');
// to slide in/out on click:
$slider.toggleClass('shown');
})
// seperate button, dedicated to fn
$('.toggleSlider').on('click', function() {
$slider.toggleClass('shown');
});
});
demo HTML
<body>
<div class='slider'>such div</div>
<button class='toggleSlider'>such div</button>
</body>
You can do it from two event attachment... and check closest() element have .spider or not and make toggle from animation() function, see below code
$(function() {
$(".slider").click(function() {
$('.slider').stop(true, false).animate({
right: "0"
}, 800, 'easeOutQuint');
});
$(document).on('click', function(e) {
if (!$(e.target).closest('.slider').length) {
$(".slider").stop(true, false).animate({
right: "-370"
}, 800, 'easeInQuint');
}
});
});
.slider {
position: fixed;
right: -370px;
top: 120px;
z-index: 99997;
width: 400px;
height: 300px;
background: red;
}
<link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div class="slider"></div>

How to detect scroll position of page using jQuery

I am having trouble with jQuery functionality on my website. What it does, is that it uses the window.scroll() function to recognize when the windows changes its scroll position and at the change calls a few functions to load data from the server.
The problem is the .scroll() function is called as soon as there is even a little change in the scroll position and loads data at the bottom; however, what I wish to achieve is to load new data when the scroll/page position reaches at the bottom, like it happens for Facebook feed.
But I am not sure how to detect scroll position using jQuery?
function getData() {
$.getJSON('Get/GetData?no=1', function (responseText) {
//Load some data from the server
})
};
$(window).scroll(function () {
getData();
});
You can extract the scroll position using jQuery's .scrollTop() method
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
// Do something
});
You are looking for the window.scrollTop() function.
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > some_number) {
// do something
}
});
Check here DEMO http://jsfiddle.net/yeyene/Uhm2J/
function getData() {
$.getJSON('Get/GetData?no=1', function (responseText) {
    //Load some data from the server
})
};
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
// getData();
}
});
$(window).scroll( function() {
var scrolled_val = $(document).scrollTop().valueOf();
alert(scrolled_val+ ' = scroll value');
});
This is another way of getting the value of scroll.
Now that works for me...
$(document).ready(function(){
$(window).resize(function(e){
console.log(e);
});
$(window).scroll(function (event) {
var sc = $(window).scrollTop();
console.log(sc);
});
})
it works well... and then you can use JQuery/TweenMax to track elements and control them.
Store the value of the scroll as changes in HiddenField when around the PostBack retrieves the value and adds the scroll.
//jQuery
jQuery(document).ready(function () {
$(window).scrollTop($("#<%=hidScroll.ClientID %>").val());
$(window).scroll(function (event) {
$("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
});
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
$(window).scrollTop($("#<%=hidScroll.ClientID %>").val());
$(window).scroll(function (event) {
$("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
});
});
//Page Asp.Net
<asp:HiddenField ID="hidScroll" runat="server" Value="0" />
You can add all pages with this code:
JS code:
/* Top btn */
$(window).scroll(function() {
if ($(this).scrollTop()) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
var top_btn_html="<topbtn id='toTop' onclick='gotoTop()'>↑</topbtn>";
$('document').ready(function(){
$("body").append(top_btn_html);
});
function gotoTop(){
$("html, body").animate({scrollTop: 0}, 500);
}
/* Top btn */
CSS CODE
/*Scrool top btn*/
#toTop{
position: fixed;
z-index: 10000;
opacity: 0.5;
right: 5px;
bottom: 10px;
background-color: #ccc;
border: 1px solid black;
width: 40px;
height: 40px;
border-radius: 20px;
color: black;
font-size: 22px;
font-weight: bolder;
text-align: center;
vertical-align: middle;
}
$('.div').scroll(function (event) {
event.preventDefault()
var scroll = $(this).scrollTop();
if(scroll == 0){
alert(123)
}
});
This code for chat_boxes for loading previous messages
GET Scroll Position:
var scrolled_val = window.scrollY;
DETECT Scroll Position:
$(window).scroll
(
function (event)
{
var scrolled_val = window.scrollY;
alert(scrolled_val);
}
);

jQuery scrolling text on hover

I have a "a" element that I want to scroll left on hover. To do this I remove the first character and append it to the end of the string.
How can I continuously fire up the scroll function?
Mouse enters element -> scroll() is fired until mouse leaves the element or user clicks on it.
html:
this text scrolls on hover
jQuery:
$(".scrollthis").hover(function(){
scroll($(this));
});
function scroll(ele){
var s = $(ele).text().substr(1)+$(ele).text().substr(0,1);
$(ele).text(s);
}
Use setInterval() to call it repeatedly from mouseenter, then clearInterval() to stop it on mouseleave:
var intervalID;
$(".scrollthis").hover(function(){
var $this = $(this);
intervalID = setInterval(function() {
scroll($this);
}, 100);
}, function() {
clearInterval(intervalID);
});
Note that you don't need to use $(ele) in your scroll() function because ele is already a jQuery object:
function scroll(ele){
var s = ele.text().substr(1)+ele.text().substr(0,1);
ele.text(s);
}
Demo: http://jsfiddle.net/hTBZn/
You can make your scroll() function a bit neater if you use the callback syntax of the .text() method (or even move that one line directly into the .hover code):
function scroll(ele){
ele.text(function(i,val) { return val.substr(1) + val.substr(0,1); });
}​
Demo: http://jsfiddle.net/hTBZn/1/
Here's the full code, you can try it out as a jsfiddle
function scroll(ele){
var s = $(ele).text().substr(1)+$(ele).text().substr(0,1);
$(ele).text(s);
}
scrollInterval = null;
function startScrolling(e) {
if (!scrollInterval) {
scrollInterval = setInterval(function(){
scroll(e)
},100);
}
}
function stopScrolling(e) {
clearInterval(scrollInterval);
scrollInterval = null;
}
$(".scrollthis").hover(function(){
startScrolling($(this));
});
$(".scrollthis").mouseout(function(){
stopScrolling($(this));
});
$(".scrollthis").mousedown(function(){
stopScrolling($(this));
});
​
css
div.container{
width: 130px;
}
div.title-holder {
width: 130px;
height:20px;
text-align:center;
background: silver;
overflow:hidden;
position: relative;
}
div.title-holder a {
position: relative;
white-space:nowrap;
left: 0px;
}
div.image{
background: brown;
width: 100%;
height: 100px;
}​
html
<div class="container">
<div class="title-holder">
long text that needs to scroll, long text that needs to scroll, long text that needs to scroll
</div>
</div>​
js
$(function(){
var scroll_text;
$('div.container').hover(
function () {
var $elmt = $(this);
scroll_text = setInterval(function(){scrollText($elmt);}, 5);
},
function () {
clearInterval(scroll_text);
$(this).find('div.title-holder a').css({
left: 0
});
}
);
var scrollText = function($elmt){
var left = $elmt.find('div.title-holder a').position().left - 1;
left = -left > $elmt.find('div.title-holder a').width() ? $elmt.find('div.title-holder').width() : left;
$elmt.find('div.title-holder a').css({
left: left
});
};
});​

Categories