I'm trying to move a div to one side or the other depending on it's position, BUT! no matter what method I use to chance its position, it doesn't really change.
var $ancho = $(document).width();
var $posP = $("#portafolio").offset().left;
var $porP = Math.floor($posP * 100 / $ancho);
the var porP saves the percentage of the div's (portafolio) position
Now, the initial position of portafolio is 13(%)
if($porP == '13')
{
$("#portafolio").mouseenter(function(){
$("#imge").stop().fadeTo('500', 0.3, function() {});});
$("#portafolio").mouseleave(function(){
$("#imge").stop().fadeOut('500', function() {});
});
$("#portafolio").click(function(){
$("#portafolio").animate({
left: "+=87%",},
{ queue: false, duration: 900, easing:'swing' });
$("#imge").fadeTo('500', 0.3, function() {
});
$(iframe).attr('src','portafolio.html');
$("#marco").fadeTo('500', 1 , function() {});
$(iframe).open();
});
}
but even when I move portafolio to the right, in the animation function, the porP var still shows 13, therefore it never reaches the else
else
{ move to the other side }
I already tried to assign a new value to the porP var inside the click function but to no avail. It just always executes the IF statement.
Does someone know why the value (porP) doesn't change? and how can I actually change it to make the else finally work?
I searched everywhere and tried everything that came to my mind with my very limited knowledge of jquery and got to nowhere. Please!!
edit// #portafolio is a relative positioned div to its parent #contenido which is absolute positioned and is left 20px . #portafolio is left 15% . I don't know if that has something to do.
Alice, I'm not sure exactly what you're trying to do, but the if and else statements probably should be inside the 'click()' handler. Something like,
$("#portafolio").click(function(){
var $ancho = $(document).width();
var $posP = $("#portafolio").offset().left;
var $porP = Math.floor($posP * 100 / $ancho);
if($porP == '13')
{
$("#portafolio").animate({
left: "+=87%",},
{ queue: false, duration: 900, easing:'swing' });
$("#imge").fadeTo('500', 0.3, function() {
});
$(iframe).attr('src','portafolio.html');
$("#marco").fadeTo('500', 1 , function() {});
$(iframe).open();
}
else
{ move to the other side }
});
Related
How can I make this js affect only the child elements of the original hovered element without giving all of the individual .g_scroll or .left/.right tags id's?
function loopRight(){
$('.g_scroll').stop().animate({scrollLeft:'+=20'}, 'fast', 'linear', loopRight);
}
function loopLeft(){
$('.g_scroll').stop().animate({scrollLeft:'-=20'}, 'fast', 'linear', loopLeft);
}
function stop(){
$('.g_scroll').stop();
}
$('#right').hover(function () {
loopRight().children();
},function () {
stop();
});
$('#left').hover(function () {
loopLeft();
},function () {
stop();
});
JSfiddle for (confusing, but necessary) html structure: https://jsfiddle.net/6rbn18cL/
To demonstrate how it would have to be renamed: https://jsfiddle.net/z9u3azqy/
So here, I "merged" both arrow handlers.
Then, there is a calculation needed to determine the "scroll" speed, based on width to be scrolled, which may no always be 100% of the element's width.
This script allows you to easily determine a speed for 100% scrolling.
Then, it calculates the speed if there is already a distance scrolled.
$(document).ready(function(){
function moveit(arrow){
// Adjust you delay here
var delay = 2000; // delay to scroll 100%
var animationDelay;
var slider = arrow.siblings(".g_scroll");
var distance = slider.width();
var scrolled = slider.scrollLeft()+1; // +1 is to avoid infinity in the math below
if(arrow.hasClass("scroller_l")){
distance = -distance;
animationDelay = -distance * (-distance/delay)*(-distance+scrolled);
}else{
animationDelay = distance * (distance/delay)*(distance-scrolled);
}
slider.stop().animate({scrollLeft:distance}, animationDelay, 'linear');
}
function stop(arrow){
arrow.siblings(".g_scroll").stop();
}
$('.scroller_l, .scroller_r').hover(function(){
moveit($(this));
},function() {
stop($(this));
});
}); // ready
CodePen
--First answer--
First, you can't use the same id more than once.
So I removed id="left" and id="right" from your HTML.
Now the trick is to pass which arrow is hovered to your functions, using $(this).
And find the .g_scroll element which is a sibling of it.
$(document).ready(function(){
function loopRight(arrow){
arrow.siblings(".g_scroll").stop().animate({scrollLeft:'+=20'}, 'fast', 'linear', loopRight);
}
function loopLeft(arrow){
arrow.siblings(".g_scroll").stop().animate({scrollLeft:'-=20'}, 'fast', 'linear', loopLeft);
}
function stop(arrow){
arrow.siblings(".g_scroll").stop();
}
$('.scroller_r').hover(function(){
loopRight($(this));
},function() {
stop($(this));
});
$('.scroller_l').hover(function(){
loopLeft($(this));
},function() {
stop($(this));
});
});
CodePen
You can pass the event object and find the proper container from there.
$('.scroller_l').hover(loopRight, stop);
$('.scroller_r').hover(loopLeft, stop);
This is done automatically if you pass functions as parameters like the above.
To find the scrolling container dynamically for each instance you can use the classes to find the container relative to the current target:
var el = $(ev.currentTarget),
parent = el.closest('.country_holder'),
container = parent.find('.g_scroll');
See a working example here.
At this point you can ask yourself whether loopRight and loopLeft can be combined in one function. The only difference is the '-=20' and '+=20'.
With polymorphism you can refactor this even further.
I made a simple content/box slider which uses the following javascript:
$('#left').click(function () {
$('#videos').animate({
marginLeft: '-=800px'
}, 500);
});
$('#right').click(function () {
$('#videos').animate({
marginLeft: '+=800px'
}, 500);
});
Here is the demo: http://jsfiddle.net/tjset/2/
What I want to do and I can't figure out how to show and hide arrows(left and right box) as the all the boxes slided.
So I clicked 4 time to the LEFT and slided all the boxes! then hide "left" so that you can't give more -800px
What can I do?
What you can do is check after the animation completes to see if the margin-left property is smaller or larger than the bounds of the video <div>. If it is, depending on which navigation button was clicked, hide the appropriate navigation link.
Check out the code below:
$('#left').click(function () {
// reset the #right navigation button to show
$('#right').show();
$('#videos').animate({
marginLeft: '-=800px'
}, 500, 'linear', function(){
// grab the margin-left property
var mLeft = parseInt($('#videos').css('marginLeft'));
// store the width of the #video div
// invert the number since the margin left is a negative value
var videoWidth = $('#videos').width() * -1;
// if the left margin that is set is less than the videoWidth var,
// hide the #left navigation. Otherwise, keep it shown
if(mLeft < videoWidth){
$('#left').hide();
} else {
$('#left').show();
}
});
});
// do similar things if the right button is clicked
$('#right').click(function () {
$('#left').show();
$('#videos').animate({
marginLeft: '+=800px'
}, 500, 'linear', function(){
var mRight = parseInt($('#videos').css('marginLeft'));
if(mRight > 100){
$('#right').hide();
} else {
$('#right').show();
}
});
});
Check out the jsfiddle:
http://jsfiddle.net/dnVYW/1/
There are many jQuery plugins for this. First determine how many results there are, then determine how many you want visible, then use another variable to keep track with how many are hidden to the left and how many are hidden to the right. So...
var total = TOTAL_RESULTS;
var leftScrolled = 0;
var rightScrolled = total - 3; // minus 3, since you want 3 displayed at a time.
instead of using marginLeft I would wrap all of these inside of a wrapper and set the positions to absolute. Then animate using "left" property or "right". There's a lot of code required to do this, well not MUCH, but since there are many plugins, I think you'd be better off searching jquery.com for a plugin and look for examples on how to do this. marginLeft is just not the way to go, since it can cause many viewing problems depending on what version of browser you are using.
i have this game :http://jsfiddle.net/Qfe6L/5/
i am trying to detect when a shuriken hit an enemy so when it hit it the enemy should disappear and the score should be increased by 1 what i searched for is that i should calculate the position of the two images to check whether their is a collision but i don't seem i can do that any help from you guys ?
$(window).keypress(function (e) {
if (e.which == 32) {
CreateChuriken();
$("#Shuriken" + Shurikengid).animate({ left: '+=300px' }, 'slow');
if ($(".Shuriken").css('left') == $(".Enemy").css('left'))
{ alert("Met"); }
}
});
You need to check for collision in each animation step. Fortunately jQuery .animate() has a progress option, which you can pass a function to be called every frame.
$("#Shuriken" + Shurikengid).animate(
{ left: '+=300px' },
{ duration : 'slow',
progress: function(){
/* collision detection here */
}
}
);
Keep in mind that
if ($(".Shuriken").css('left') == $(".Enemy").css('left'))
will only compare position of first projectile and first enemy, while there are more of them on the screen. You need to iterate over every projectile and compare its powition with every enemy to find a colliding pair, like:
$('.Shuriken').each( function(){
var sOffset = $(this).offset();
$('.Enemy').each( function(){
var eOffset = $(this).offset();
if( sOffset.left == eOffset.left ){
/* boom! */
}
});
});
The above is close, but still won't work. Animation doesn't progress by 1px each frame, so you may go from Shuriken at 100px left and Enemy at 101px left at one frame to Shuriken at 102px left and Enemy at 99px left in the next one. They'll pass each other, but won't meet at the same point. So you'd need to round these values to, say, nearest 10s which will give you a bigger tolerance. You sholud also compare the vertical positions.
Updated fiddle: http://jsfiddle.net/Qfe6L/8/
(Fixed vertical posiotion of Enemies for easier testing).
Edit:
as suggested by #Kasyx it would be better to move all of this out of animation function and create a Game Loop and Scene Graph. Scene graph would keep track of elements' positions, and within Game Loop you'd check for collisions, then call a rendering function which would draw elements on screen based on the scene graph.
At the moment you’re running your hit check function once, directly after you’ve started the animation. What you need to be doing is running it every frame to see the intersect. Luckily jQuery provides a callback handler for this: $.animate’s step option. If you pass a second object into $.animate you can specify both your duration and step function like so:
$(window).keypress(function (e) {
if (e.which == 32) {
CreateChuriken();
$("#Shuriken" + Shurikengid).animate({
left: '+=300px'
}, {
duration: 'slow',
step: function(){
if ($(".Shuriken").css('left') == $(".Enemy").css('left')) {
alert("Met");
}
}
});
}
});
As you’re calling your step function once every frame you’ll want to cache your selectors inside ($('.Shuriken'), $('.Enemy')) first:
$(window).keypress(function (e) {
if (e.which == 32) {
var shuriken, enemy;
CreateChuriken();
shuriken = $('.Shuriken');
enemy = $('.Enemy');
$("#Shuriken" + Shurikengid).animate({
left: '+=300px'
}, {
duration: 'slow',
step: function(){
if (shuriken.css('left') == enemy.css('left')) {
alert("Met");
}
}
});
}
});
I am doing some research at the moment into creating a new maths game for primary school children where divs from 0-9 appear at random inside a container.
A question is given at the beginning. Something like, multiples of 20. The user will then have to click on the correct ones, and they will then be counted at the end and a score will be given.
I have just changed the speed in which the divs appear so that they appear for longer and more than one at a time to make the game easier for younger children.
I used "fadeIn" like so..
$('#' + id).animate({
top: newY,
left: newX
}, 'slow', function() {}).fadeIn(2000);
}
My problem is that now when I shoot the correct or incorrect number the animation is very glitchy and I cannot figure out why.
Fiddle: http://jsfiddle.net/cFKHq/6/ (See version 5 to see what it was like before)
Inside startplay(), control the concurrency when calling scramble() , I do it with a global var named window.cont, so I replaced your following call:
play = setInterval(scramble, 1800);
for this one:
play = setInterval(function() {
if (window.cont){
window.cont = false;
scramble();
}
}, 1000);
The var window.cont needs to be set globally at the start of your code, like so:
var miss = 0;
var hit = 0;
var target = $("#target");
window.cont = true;
So with window.cont you now can control that animations are executed one after another, without overlapping, like so:
$('#'+id).css({
top: newY,
left: newX
}).fadeIn(2000, function() {
setTimeout(function() {
$('#' + id).slideUp('fast');
window.cont = true;
}, 1500);
});
See working demo
Its getting a bit late so excuse me if I am making a stupid mistake. For some reason the following code:
$(".myClass").each(function(){
widths[$(this).attr("id")] = $(this).width();
if ($(this).attr("id") != $(clickedExpand).attr("id"))
{
$(this).animate({
width: '10px'
});
}
});
The array is initialized as
var widths = new Array();
earlier in the code. For some reason, despite the fact that I am recording the the widths before the animation begins, I am getting post-animation values in the array. It seems as though the animation finishes and then the values get recorded. I have tried to take it out of the function and wrap it in another .each but I am getting the same result.
Any help is would be greatly appreciated!
entire code:
var slateWidths = {};
$(".slateExpand").click(function(){
var clickedExpand = $(this).closest(".slate");
$(".slate").each(function(){
slateWidths[$(this).attr("id")] = $(this).outerWidth();
if ($(this).attr("id") != $(clickedExpand).attr("id"))
{
$(this).animate({
width: '10px'
});
$(this).find($('.slateExpand')).hide();
}
});
$(this).text("Restore");
$(this).removeClass("slateExpand").addClass("slateRestore");
$(".slateRestore").on("click",function(){
$(".slate").each(function()
{
alert(slateWidths[$(this).attr("id")]);
//var width = slateWidths[$(this).attr("id")];
$(this).animate({
width: slateWidths[$(this).attr("id")]
});
});
});
});
// first of all save all widths for all .slate
var slateWidths = {};
$(".slate").each(function(){
slateWidths[$(this).attr("id")] = $(this).width();
});
$(".slateExpand").click(function(){
var $slate = $(this).closest('slate');
if($slate.hasClass('hidden')) {
$slate.animate({
width: slateWidths[$slate.attr('id')]
});
$(this).text("hide");
$slate.removeClass("hidden")
}else{
$slate.animate({
width: '10px'
});
$(this).text("Restore");
$slate.addClass("hidden")
}
});
Ok, if you come across a similar issue, there is an easy solution. The issue is that the click has not be unbound the event from the div despite the class change. As a result, it first reruns the code that records the widths. This causes the animation to not play since now the previous widths are the same as the current ones. To solve this, simply add
$("theDiv").unbind("click);
to remove the event handler. This will prevent the click event which is for the previous class from firing.