JS from HOVER to ONLOAD - javascript

i'm trying to edit some existing code to fulfill my need.
https://tympanus.net/codrops/2010/02/08/awesome-css3-jquery-slide-out-button/
It's effect of sliding out content after you hover over it with the mouse is what i am after. Seems simple enough, but i would rather have it on a (automatic) timer. Or rather have no interaction from the user at all for it to work.
Let's say it starts closed, then opens up after 2 seconds. Stays open voor 5 seconds and then closes again. All without using the mouse to activate it.
<script type="text/javascript">
$(function() {
$('.slidebttn').hover(
function open() {
var $this = $(this);
var $slidelem = $this.prev();
$slidelem.stop().animate({'width':'225px'},800);
$slidelem.find('span').stop(true,true).fadeIn();
$this.addClass('button_c');
},
function close() {
var $this = $(this);
var $slidelem = $this.prev();
$slidelem.stop().animate({'width':'70px'},700);
$slidelem.find('span').stop(true,true).fadeOut();
$this.removeClass('button_c');
}
);
});
</script>
Any tips on what i need to edit to reach my goal?
JSFiddle: https://jsfiddle.net/mj7yumfw/14/

Try this one:
<script type="text/javascript">
$(function() {
setTimout(initSlider, 2000);
});
function initSlider() {
open();
setTimeout(close, 5000);
}
function open() {
var $this = $('.slidebttn');
var $slidelem = $this.prev();
$slidelem.stop().animate({'width':'225px'},800);
$slidelem.find('span').stop(true,true).fadeIn();
$this.addClass('button_c');
}
function close() {
var $this = $('.slidebttn');
var $slidelem = $this.prev();
$slidelem.stop().animate({'width':'70px'},700);
$slidelem.find('span').stop(true,true).fadeOut();
$this.removeClass('button_c');
}
</script>
What is different here is that it's using timeout functions to initialize and close slider. These two function (initialize and close) are separated, so you can use them whenever you want.
You can manipulate the time when you're slider opens and closes.
Opening time is 2000 right now, which means (~2s) and closing is 5000 (~5s).
It will work only when the buttons are available as the element to slide is found using .slidebttn element.

Related

Pause simple fader script on mouse-hover

I would like pause on hover when the mouse hovers over the fadelinks div for this script:
$(function(){
$('.fadelinks > :gt(0)').hide();
setInterval(function(){$('.fadelinks > :first-child').fadeOut().next().fadeIn().end().appendTo
('.fadelinks');}, 5000);
});
The html is along the lines of:
<div class="fadelinks">
<div>...</div>
<div>...</div>
</div>
I've tried a few things relating to interval to try and cram pause on hover functionality in there, but with my extremely limited jquery knowledge, everything I've tried breaks the script, leaving it stuck on the last slide or the first slide. Would just like this simple script to pause on mouse-hover and start up again on mouse-exit.
Here's a JSFiddle of the script in its natural state.
Try using .hover() , declaring variable to reference setInterval , using a function to call setInterval
$(function(){
// define `_interval` variable
var _interval;
// cache `.fadelinks` element
var elem = $(".fadelinks");
elem.find("> :gt(0)").hide();
elem.hover(function() {
// "pause" at `hover` of `.fadelinks`
clearInterval(_interval)
}, function() {
// "reset"
interval()
});
var interval = function() {
_interval = setInterval(function(){
elem.find("> :first-child")
.fadeOut().next().fadeIn().end()
.appendTo(elem);
}, 2000)
};
interval()
});
jsfiddle https://jsfiddle.net/ccmgdfog/4/
In your case, there wasn't the need for jQuery. Only with stopInterval you can control it. Altrough there is the jQuery $.stop() function, we wouldn't get the desired result.
I've changed a bit your code:
$(function(){
$('.fadelinks > :gt(0)').hide();
var interval = setInterval(intervalFunc, 2000);
$('.fadelinks').on('mouseenter',function(){
clearInterval(interval);
});
$('.fadelinks').on('mouseout',function(){
interval = setInterval(intervalFunc, 2000);
});
function intervalFunc(){
$('.fadelinks > :first-child').fadeOut().next().fadeIn().end().appendTo('.fadelinks');
}
});

jQuery AUTOMATIC scroll (no button click) on document ready

I am creating a chat, everything works perfectly, it scrolls down when i click the "Send" button, but I want it to scroll all the way down when the document is ready. I have done this by adding the scrolling function to setInterval, but the problem with that is that the user basically cant scroll up to see previous chat messages because he gets scrolled down every 0.1 seconds. My code is:
$(function () {
//$("#messages").scrollTop($("#messages").prop("scrollHeight")); Doesnt work at all
function updateChat(){
$("#messages").load('chat/ajaxLoad.php');
//$("#messages").scrollTop($("#messages").prop("scrollHeight")); This works but the user cannot scroll up anymore
}
setInterval(function () {
updateChat();
}, 100);
$("#post").submit(function(){
$.post("chat/ajaxPost.php", $('#post').serialize(), function (data) {
$("#messages").append('<div>'+data+'</div>');
$("#messages").scrollTop($("#messages").prop("scrollHeight")); // This works but only when the user presses the send button
$("#text").val("");
});
return false;
});
});
Add this to your code.
var chat = $("#messages").html();
setInterval(function () {
updateChat();
if(chat !== $("#messages").html()){
$("#messages").scrollTop($("#messages").prop("scrollHeight"));
chat = $("#messages").html();
}
}, 2000);
I think this should work (didnt test), but there are some better ways you can optimise this like not saving the whole .html() into a variable.
The idea here is that it checks if the content is changed every 2 seconds. If it is, it scrolls down.
I see what's your problem and I have 2 ideas for you :
You scroll down only when a new message is post, for example with an Ajax request you could check if number of messages is > in compare with the last 0.1s, if yes you scroll if not you ignore.
You scroll down every 1-2s only if the scroll is at the maximum bottom position. If the scroll is not at the maximum you do not scroll. I feel this solution is better.
You need to seperate the actions on your application,
also you missed many checks that can make the application work properly and will
make it easy to maintain.
How i suggestion the code will look:
$(function () {
function updateMessages(){
var messages_before_update = $("#messages").html();
$("#messages").load('chat/ajaxLoad.php');
var message_after_update = $("#messages").html();
if(messages_before_update !== message_after_update){
scrollToBottom();
}
}
function scrollToBottom(){
var scroll_height = $("#messages").prop("scrollHeight");
var scroll_top = $("#messages").scrollTop();
if(scroll_height !== scroll_top){
$("#messages").scrollTop($("#messages").prop("scrollHeight"));
}
}
function addMessage(message){
$("#messages").append('<div>' + message + '</div>');
}
setInterval(updateMessages, 100);
$("#post").submit(function () {
$.post("chat/ajaxPost.php", $('#post').serialize(), function (data) {
addMessage(data);
scrollToBottom();
$("#text").val("");
});
return false;
});
});

Temporary creation of html div using Jquery

I am trying to create div's on demand which then timeout and are then hidden and removed from the dom.
The display property of "load_bar" is set to none so that I can use the last selector to get a reference to the instance I have just created.
It is important that this solution can create several div's which are running on their own timeout clock
$(document).ready(function () {
$('#add').click(function () {
var t = Math.random()*20;
alert(t);
var destination = $('input').val();
$('#holding_pen').append('<div class="load_bar">'+destination+'</div>');
$('.load_bar:last').show().delay(t).hide().remove();
});
});
Every thing works to create divs when I remove .delay().hide().remove();
However when I add this the div is not shown at all
Create proper elements, that way you'll have a reference to the element within the function:
$(document).ready(function () {
$('#add').click(function () {
var t = (Math.random()*20)*1000,
destination = $('input').val(),
div = $('<div />', {'class':'load_bar', text: destination});
$('#holding_pen').append(div);
div.show(1).delay(t).hide(1, function() {
$(this).remove();
});
});
});
Also, hide() and show() does not work with the animation queue and subsequently not with delay() unless a duration is given, and that's why the element is never shown, delay() doesn't work and the element is hidden right away.
EDIT:
Also, remove() is not an animated method, so it doesn't work with delay(), but hide() a useful callback for that, see edited code above.
FIDDLE
The problem is because delay is used to stop jQuery animation queue, which both show and hide do not use. Therefore your div is being shown and them immediately hidden. Use setTimeout instead:
$('#add').click(function () {
var destination = $('input').val();
$('#holding_pen').append('<div class="load_bar">'+destination+'</div>');
$('.load_bar:last').show();
setTimeout(function() {
$('.load_bar:last').hide();
}, Math.random() * 20 * 1000); // * 1000 = seconds
});
Example fiddle
The delay() function only applies to actions queued on the element.
$(document).ready(function () {
$('#add').click(function () {
var t = Math.random()*20;
alert(t);
var destination = $('input').val();
$('#holding_pen').append('<div class="load_bar">'+destination+'</div>');
$('.load_bar:last').show().delay(t).queue(function( nxt ) {
$(this).hide().remove();
nxt(); // continue the queue
});
});
});
$(document).ready(function () {
$('#add').click(function () {
var t = Math.random()*20;
alert(t);
var destination = $('input').val();
$('#holding_pen').innerHTML='<div class="load_bar">'+destination+'</div>';
});
});

Clearing timeouts with javascript

i'm having some sort of variable out of scope issue or something. in the function below, i'm creating or clearing a timeout based on whether the mouse is entering or exiting. it seems though, that even once the timeout has been created it's returning undefined on re-entry. not sure what i'm doing wrong here, thanks for your help!
jsFiddle example
JavaScript: (particular issue is within else conditional on line 35
var navLinks = $('nav li.sub');
navLinks.mouseenter(function(){
console.log('hovering on link');
var thiis = $(this),
subList = thiis.find('ul'),
autoClose;
if (!thiis.hasClass('out')){
console.log('isnt out');
/* Link */
thiis
/* Show submenu when entering link */
.addClass('out')
/* Hide submenu when exiting link */
.mouseleave(function(){
autoClose = setTimeout(function(){
thiis.removeClass('out');
}, 1000);
console.log('exiting link: timeout active', autoClose);
});
} else {
console.log ('is out', autoClose);
if (autoClose){
console.log('is out: clear timeout');
clearTimeout(autoClose);
}
}
});
Techno,
The simple answer is just to move var autoClose to an outer scope, but I think you can (and should) do more.
More specifically,
I don't think you want to attach the mouseleave handler inside the mouseenter handler. It can be permanently attached from the outset.
In the mouseenter handler, clearTimeout(autoClose) and thiis.addClass('out') can be executed unconditionally. There's no real economy in testing .hasclass('out').
Try this :
var navLinks = $('nav li.sub');
var autoClose;
navLinks.hover(function(){
var thiis = $(this);
clearTimeout(autoClose);
thiis.addClass('out');
}, function(){
var thiis = $(this);
autoClose = setTimeout(function(){
thiis.removeClass('out');
}, 1000);
});
As pointed in comments to question you have new timeout each time mouse hovers an item. Lets make new timeout variable for every item:
$('nav li:has(ul)').each(function(){
var par = $(this),
sub = $("> ul", this),
closeTO;
par.hover(
function(){
clearTimeout(closeTO);
par.addClass("out");
},
function(){
closeTO = setTimeout(function(){
par.removeClass("out");
}, 1000);
}
);
});
http://jsfiddle.net/ByuG3/1/
You should use a global object to store some vars like reference of timeout and interval.
In example you could declare such an object:
// Declare the context object in the global scope
var myContext = {
"myTimeout" : false
}
And then use the context object in your mouseenter and mouseleave handler functions.

How to determine if content in popup window is loaded

I need to set some contextData for a popup window from its parent. I try this:
var some contextData = {};
$(function() {
$('#clickme').click(function() {
var w = window.open('http://jsfiddle.net');
w.contextData = contextData
//w.context data is null in the popup after the page loads - seems to get overwritten/deleted
});
});
It doesn't work, so my next thought, wait until content is loaded
var some contextData = {};
$(function() {
$('#clickme').click(function() {
var w = window.open('http://jsfiddle.net');
w.onload = function() {
//Never Fires
w.contextData = contextData;
}
});
});
See this fiddle. My onload method never fires.
This works:
var some contextData = {};
$(function() {
$('#clickme').click(function() {
var w = window.open('http://jsfiddle.net');
setTimeout(function(){
if(w.someVariableSetByThePageBeingLoaded) {
w.contextData = contextData;
}
else{
setTimeout(arguments.callee, 1);
}
}, 1);
});
});
But has obvious elegance problems (but is the current work around).
I know you can go the other way (have the popup call back to a method on the opener/parent, but this forces me to maintain some way of looking up context (and I have to pass the key to the context to the popup in the query string). The current method lets me capture the context in a closure, making my popup a much more reusable piece of code.
I am not trying to do this cross domain - both the parent and popup are in the same domain, although the parent is an iframe (hard to test with jsfiddle).
Suggestions?
If you are doing this with an iframe try it this way
HTML
<button id="clickme">Click Me</button>
<iframe id="framer"></iframe>
​
Javascript
$(function() {
$('#clickme').click(function() {
$("#framer").attr("src","http://jsfiddle.net");
$("#framer")[0].onload = function(){
alert('loaded');
};
});
});​
I updated your jsfiddle http://jsfiddle.net/HNvn3/2/
EDIT
Since the above is completely wrong this might point you in the right direction but it needs to be tried in the real environment to see if it works.
The global variable frames should be set and if you
window.open("http://jsfiddle.net","child_window");
frames["child_window"] might refer to the other window
I got javascript access errors when trying it in jsfiddle - so this might be the right track
EDIT2
Trying out on my local dev box I was able to make this work
var w = window.open("http://localhost");
w.window.onload = function(){
alert("here");
};
the alert() happened in the parent window

Categories

Resources