I'm testing out some code for making names float around randomly. My general question is how do we apply variables to style attributes? My specific example is as follows. First I tried this:
<body>
Is this it?
<button id="go">» Run</button>
<div id="floatName" style="left:50px; top:150px">James</div>
<div id="n2">Sarah</div>
<script>$( "#go" ).click(function() {
$( "#floatName" ).animate({
left: "100px",
top: "200px"
}, 500, function() {
// Animation complete.
});
$( "#2" ).animate({
left: "300px",
top: "20px"
}, 500, function() {
// Animation complete.
});
});
</script>
</body>
This works as I expected. Next I wanted to randomize the animation to that the left and top change. However, I don't know how to do this. One try looks like this:
$( "#floatName" ).animate({
x = Math.random()*500
y = Math.random()*500
left: x + "px",
top: y + "px"
}, 500, function() {
// Animation complete.
});
Obviously didn't work and I'm having problems finding the solution.
http://jsfiddle.net/veqne72f/
$( "#floatName" ).animate({
left: Math.random()*500 + "px",
top: Math.random()*500 + "px"
}, 500, function() {
// Animation complete.
});
Related
I'm trying to create this portfolio page where there are 2 columns of images. On hover the image zooms and the next image is pushed away to reveal a caption.
I am new to javascript and I have it working but it is crashing my page after a few minutes of running. I'm sure this is not written in the best manner. anyone have feedback?
function portImage() {
$('.slide').mouseenter(
function() {
var imgResize = $(this).children('.slide-image').children('img');
var current_h = $(this).children('.slide-image').children('img').height();
var current_w = $(this).children('.slide-image').children('img').width();
$(imgResize).addClass('active');
$(imgResize).clone().insertAfter($(imgResize)).addClass('clone');
$(this).find('.active').removeClass('active');
$(this).find('.clone').filter(':not(:animated)').animate({
width: (current_w * 1.3),
height: (current_h * 1.3)
}, {queue: false, duration: 300});
}).mouseleave(
function() {
var imgResize = $(this).children('.slide-image').children('img');
var current_h = $(this).children('.slide-image').children('img').height();
var current_w = $(this).children('.slide-image').children('img').width();
$(this).find('.clone').filter(':not(:animated)').animate({
width: (current_w + 'px'),
height: (current_h + 'px')
}, {queue: false, duration: 300});
});
};
function leftSlide() {
$('.slide.left').hover(
function(){
$(this).next('.slide.right').animate({
right: "-25%"
}, 500);
$(this).children('.slide-caption').animate({
right: "-50%"
}, 500);
},
function(){
$(this).next('.slide.right').animate({
right: "0"
}, 500);
$(this).children('.slide-caption').animate({
right: "0"
}, 500);
});
};
function rightSlide() {
$('.slide.right').hover(
function(){
$(this).prev('.slide.left').animate({
left: "-25%"
}, 500);
$(this).children('.slide-caption').animate({
left: "-50%"
}, 500);
},
function(){
$(this).prev('.slide.left').animate({
left: "0"
}, 500);
$(this).children('.slide-caption').animate({
left: "0"
}, 500);
});
};
portImage();
rightSlide();
leftSlide();
I have it set up on jsfiddle:
https://jsfiddle.net/cuestadesign/jej9xrfq/
This is a result of your .clone() function in the mouseenter event handler of the portImage() function.
You are setting var imgResize to all the children imges of $(this).children('.slide-image'). The first time around this only grabs the one image. However, you then clone that image and add it as a sibling to that image. The next time around, your function will assign both images to var imgResize and clone them both/animate them both, etc...
This results in exponential growth of images being cloned and animated, resulting in a page crash after only a few iterations.
The solution? As far as I can tell, just removing the clone after it's been animated up and back down solves everything:
$(this).remove();
That would go in a callback function of the .animate() function in the mouseleave event handler of your portImage() function, like so:
$(this).find('.clone').filter(':not(:animated)').animate({
width: (current_w + 'px'),
height: (current_h + 'px')
}, {queue: false, duration: 300, complete: function() {
$(this).remove();
}
});
You may also want to change assignment of imgResize to not include items with a class of .clone:
var imgResize = $(this).children('.slide-image').children('img:not(.clone)');
JSFiddle Here
$(".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>
Why will this code not work as an onclick ?
$('.mainz11').click (function() {
$(this).animate({
height: '280px'
}, 800);
}, function() {
$(this).animate({
height: '100px'
}, 800);
});
If you're trying to first expand the element and then contract it, it should probably be something like this:
$('.mainz11').click(function() {
// determine target heights
if ($(this).hasClass("expanded")) {
var targetHeight = 100;
} else {
var targetHeight = 280;
}
// animate
$(this).animate({
height: targetHeight
}, {
duration: 800,
complete: function() { $(this).toggleClass("expanded"); }
});
});
This could use some cleaning up, but it does the trick, and you can track expanded items easily this way.
See here: http://jsfiddle.net/mpQek/3/
The click function takes only a single function but you are passing 2 functions to it. You can try it this way:
$('.mainz11').click (function() {
$(this).animate({
height: '280px'
}, 800);
});
If you want to chain animations, put the next animation as the function to run on complete of the first animation:
http://api.jquery.com/animate/
$('.mainz11').click (function() {
$(this).animate({ height: '280px', 800,
function() { $('.mainz11').animate({ height: '100px'}, 800)
);
});
I am trying to make this animation loop
$(".jquery_bounce").ready(function(){
$("img", this).animate({ marginLeft : '20px' } , {
duration: 200,
complete:function() {
$(this).animate({ marginLeft : '0px' } , {
duration: 200,
easing: 'easeInCubic',
});
}
});
})
});
<div class="example">
<h4>Bounce</h4>
<div class="jquery_bounce bounce">
<img src="images/bounceimg.png" class="bounceimg" />
</div>
</div>
Please help.
try this~
$(function(){
$.extend({
show:function(){
$(".jquery_bounce").ready(function(){
$("img", this).animate({ marginLeft : '20px' } , {
duration: 200,
complete:function() {
$(this).animate({ marginLeft : '0px' } , {
specialEasing: {
left: 'swing',
top: 'easeOutBounce'
}
});
}
});
})
}
});
setInterval("$.show()",1000);
});
Demo:
http://jsfiddle.net/VpKw2/
Why don't you use setInterval()?
Edit:
Your animation bounces once, then stops, because...
You trigger the margin=20 part.
Upon completeness, another animation is scheduled: margin=0.
That's it. It doesn't loop because nothing is rescheduled to happen after the first pass.
Read the documentation on setInterval(): it's a function that let's you call another function at fixed (in milliseconds) intervals.
If you still want to do it as above, you must fix the problem I pointed out. Try thinking your way around it, and I'll help if you can't figure it out :).
Cheers.
Setup a bounce function that will continue the animation, either moving the element left or right:
function bounce(elm, leftZero) {
var px = leftZero ? '0px' : '20px';
elm.animate({ marginLeft : px}, {
duration: 200,
complete:function(){
//Continue bouncing
setTimeout(function(){
bounce(elm, !left);
},1);
}
});
}
$(".jquery_bounce").ready(function(){
$("img", this).each(function(){
//Start bouncing
bounce($(this), false);
});
})
});
The question has to do with Firefox refreshing the browser window to 100% when a function is called.
If the browser view is at say, 75%, and I use .click method on a link - the page refreshes at 100% THEN the function executes. Safari executes the function without refreshing the window.
The code now looks like:
function hideFlag(){
$("#ftm").click(function () {
var stageWidth = $("#window_div").width();
if (stageWidth <= 1200){
$( "#window_div" ).animate({
width: 1250,
opacity: ".8",
}, 1000 );
$( "#flagDiv" ).animate({
opacity: "0",
}, 1000 );
}
else{
$( "#window_div" ).animate({
width: 500,
opacity: ".6",
}, 1000 );
$( "#flagDiv" ).animate({
opacity: "1",
}, 1000 );
}
});
}
In Firefox, if my browser view is zoomed out to 75% and I replace the .click() method with .mouseenter, the divs animate without the screen redrawing or resizing on mouseenter. I don't understand the difference between the click() and mouseenter() implementations.
Solved it.
It was far simpler than I thought. Proper use of the "return false;" argument on the click method
solved my problem. Revised code is as follows:
function hideFlag(){
$("#ftm").click(function () {
var stageWidth = $("#window_div").width();
if (stageWidth <= 1200){
$( "#window_div" ).animate({
width: 1250,
opacity: ".8",
}, 1000 ); return false;
$( "#flagDiv" ).animate({
opacity: "0",
}, 1000 ); return false;
}
else{
$( "#window_div" ).animate({
width: 500,
opacity: ".6",
}, 1000 );return false;
$( "#flagDiv" ).animate({
opacity: "1",
}, 1000 );return false;
}
});
}
Thanks all for the help.
Not that this a direct answer to your question, but it's rather long for a comment.
You're using jQuery. I think you're missing the point of the whole cross-browser-library thing. Change
stageWidth = document.getElementById("window_div").clientWidth
to
stageWidth = $("#window_div").width()
no browser-specific code needed. There also no need for that addEventHandler function when using jQuery. It takes care of the differences between browsers so that you don't have to. That means you can change the setUpClickHandler function to this:
function setUpClickHandler() {
$('#ftm').click(hideFlag);
$('#ath').click(showFlag);
}
and change showFlag to this:
function showFlag(e){
$('#flagDiv').show();
}
and change
addEventHandler(window, "load", setUpClickHandler, false);
to
$(window).load(setUpClickHandler);