I have this basic script that makes an element show onmouseenter, and hide onmouseleave.
In HTML version works fine, but i need to display it in wordpress; but in WP didn't work.
Firebug shows the following error:
sidebar_animate is not defined
How can I fix this?
The script
<script language="javascript">
function sidebar_animate(px) {
$('#sidebar').animate({
'marginLeft' : px
});
}
</script>
Body
<div id="sidebar" onmouseenter="sidebar_animate('+180px');"
onmouseleave="sidebar_animate('-20px');"
style="background-color: red; width: 240px; height: 100px; position: absolute; left: -180px;" >
This is going to move
</div>
How about binding the event handlers with jQuery so your code is all in one spot:
<script language="javascript">
//wait for document.ready to fire so elements are available to manipulate
$(function () {
//setup object to convert the type of event fired to the pixel offset to apply for the event
var eventToPx = {
mouseenter : 180,
mouseleave : -20
};
//bind an event handler to the `#sidebar` element for `mouseleave` and `mouseenter`
$('#sidebar').on('mouseenter mouseleave', function (event) {
//animate this element's `margin-left` property to the specified number of pixels
//note that jQuery assumes pixels if you omit units
$(this).stop().animate({
marginLeft : eventToPx[event.type]
}, 500);
});
});
</script>
Here is a demo: http://jsfiddle.net/jasper/mYwqE/
Notice that I added .stop() to your code just before the .animate() call. It will stop the current animation if a new one is queued, so the animations won't queue-up if the user mouse-over's and mouse-out's the element many times rapidly.
Note that .on() is new as of jQuery 1.7 and in this case is the same as using .bind(): http://api.jquery.com/on
Related
I have an object which is animated and falling from the top of the window to the bottom of the window. this works fine, but I would like to return the position of the element continuously.
At the moment I have this code
var pos = function() {
console.debug(jQuery('.element').position());
}
jQuery(window).on('mousemove', pos);
Which returns the position of the class "element" when the mouse is moving, I have also tried the event handler "live" but it is not working.
Is there any event handler I can use which will continuously return the position of them elemnt?
Thank you
Use .animate()'s step callback to track whatever you want, from position to timing:
var $test = $("span");
$("#element").animate({ top: 300 }, {
duration: 5000,
step: function(now, fx) {
$test.text( now );
}
});
#element{
position:absolute;
top: 0;
background:red;
width:40px;
height:40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span> px
<div id="element"></div>
http://api.jquery.com/animate/
A small suggestion, if you don't want to lose your fingers writing jQuery all over the place....
jQuery(function( $ ){ // DOM ready and jQuery $ alias secured
// Free to use $ as you usually would
});
You could use setInterval to execute a function at given interval.
setInterval(function () {
// do something here
}, 1000); // each 1 sec, starts after 1s
I am using zepto library for my mobile web site. I have recently learnt that zepto does not have slideDown() plugin like jquery. I would like to implement the same for zepto.
I have tried one on jsfiddle (http://jsfiddle.net/goje87/keHMp/1/). Here it does not animate while showing the element. It just flashes down. How do I bring in the animation?
PS: I cannot provide a fixed height because I would be applying this plugin to the elements whose height property would not be known.
Thanks in advace!!
Demo: http://jsfiddle.net/6zkSX/5
JavaScript:
(function ($) {
$.fn.slideDown = function (duration) {
// get old position to restore it then
var position = this.css('position');
// show element if it is hidden (it is needed if display is none)
this.show();
// place it so it displays as usually but hidden
this.css({
position: 'absolute',
visibility: 'hidden'
});
// get naturally height
var height = this.height();
// set initial css for animation
this.css({
position: position,
visibility: 'visible',
overflow: 'hidden',
height: 0
});
// animate to gotten height
this.animate({
height: height
}, duration);
};
})(Zepto);
$(function () {
$('.slide-trigger').on('click', function () {
$('.slide').slideDown(2000);
});
});
This worked for me:
https://github.com/Ilycite/zepto-slide-transition
The Zepto Slide Transition plugin add to Zepto.js the functions bellow :
slideDown();
slideUp();
slideToggle();
Speransky's answer was helpful, and I'm offering a simplified alternative for a common drop-down navigation list, and separated into slideUp and slideDown on jsfiddle: http://jsfiddle.net/kUG3U/1/
$.fn.slideDown = function (duration) {
// show element if it is hidden (it is needed if display is none)
this.show();
// get naturally height
var height = this.height();
// set initial css for animation
this.css({
height: 0
});
// animate to gotten height
this.animate({
height: height
}, duration);
};
This would work for what you need:
https://github.com/NinjaBCN/zepto-slide-transition
I am trying to do a mouseover event for one picture where when you mouseover a div comes up and animates on the picture. When I do my mouseover though, it brings up both divs for separate pictures when I only want one at a time. Here is my code. The first part is the mouseover. Second is mouseout.
$('.portfolio img').mouseover(function(){
$(this).css('cursor', 'pointer');
$(this).parent().find('img:first').stop().animate({opacity:1}, 800, function() {
$("div.folio").animate({ height: '+=25px', top: '-=24px' }, 100, function() {
$("div.folio span").animate({ opacity: 1 }, 500);
});
});
});
$('.img_grayscale').mouseout(function(){
$(this).stop().animate({opacity:0}, 800, function() {
$("div.folio span").animate({ opacity: 0 }, 500, function() {
$("div.folio").animate({ height: '-=25px', top: '+=24px' }, 100);
$("div.folio").css('top', '-9px');
});
});
});
<div class="portfolio">
<h2>The Portfolio</h2>
<p class="slideTwo">Check out some of our recent projects.</p>
<ul>
<li><img src="portfolioOne.jpg"></img><div class="folio"><span>thesite.com</span></div></li>
<li><img src="portfolioOne.jpg"></img><div class="folio"><span>mysite.com</span></div></li>
</ul>
</div>
Using jQuery's $("div.folio") will return all divs with a class of "folio". Since you are seeing this animation on both images, rather than just the one you've moused-over, I'm assuming they both have the same class on the div they want to animate. In order to only animate one, you'll need to be more specific when selecting it with jQuery. Including $(this) on the path to the div to animate usually works, but I can't tell you the exact code without the corresponding HTML.
You need to cancel the bubble up event by returning "false" from your event handler.
$('.portfolio img').mouseover(function(){
// Your logic here...
return false;
});
There are a couple of concerns that I have about this which may or may not be problematic depending on what else is going on that you haven't shown.
You're doing $(this).parent().find('img:first') inside of a jQuery onmouseover function where $(this) should already be representing the img that you care about. Did you find that was necessary for some reason?
You could be more specific in your selector. Try doing $(".portfolio>ul>li>img")
img_grayscale is only mentioned once in your markup in your question so I'm not sure how that class gets applied but I'm assuming it does.
You could just add the class portfolio (or some unique identifier) to your images directly and probably have an easier time figuring out exactly why it isn't working as you expect. Then your mouseover selector could just be $(".specialClass")
You should definitely try posting a jsfiddle.net; you could borrow any two images off the web for testing.
Managed to figure this one out. I had to basically transverse the DOM through the following code. I referenced the image and then I went to the parent then to the next element in the DOM which was my div of div.folio. Then I went to the child of that object to fade it in. I did the same thing in reverse basically on the mouseout.
$('.portfolio img').mouseover(function(){
$(this).css('cursor', 'pointer');
$(this).parent().find('img:first').stop().animate({opacity:1}, 800, function() {
$(this).parent().next().animate({ height: '+=25px' }, 100, function() {
$(this).children().animate({ opacity: 1 }, 100);
});
});
});
$('.img_grayscale').mouseout(function(){
$(this).stop().animate({opacity:0}, 800, function() {
$(this).parent().next().children().animate({ opacity: 0 }, 100, function() {
$(this).parent().animate({height: '-=25px' }, 100);
});
});
});
I have an HTML element that I need to track another element. Specifically, I need to have the top left and top right corners of both elements be positioned the same. When a window gets resized, the resize event gets triggered and I can adjust the position of the dependent element. However, if the element being tracked is repositioned (but not resized), I do not see any DOM event.
How can we find out if a DOM element has been moved? We are using the latest jQuery.
Here is a code sample.
Note that elementOne and mouseTracking divs are there to show elements that get moved for "some" reason that is outside the control of my code.
This code works for the elementOne case.
MouseTrackingTracker does not track a moving element.
ResizerTracker does not put the border around the complete text in the overflow case.
I would like the trackingDivs to move and resize no matter the reason for the tracked element's reasons for changing.
This code relies on the window resize being the hooked event. Hooking some event that fires when the element changes its dimensions is closer to what I need.
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js"></script>
<style type="text/css">
#elementOne { float : right;width : 200px; display:inline-block}
#resizer { float : left; display:inline-block}
.trackedDiv { width:50px; height:50px; background-color: blue }
.trackingDiv { position:absolute; z-index: 1; border:3px green; border-style: solid;}
</style>
<script>
$(function() {
$( window ).bind("resize",function(){
$("#elementOne").trigger("reposition");
$("#mouseTracking").trigger("reposition");
$("#resizer").trigger("reposition");
});
var repositionFunction = function(selfish, element){
var self = $(selfish);
var offset = self.offset();
var selfTop = offset.top;
var selfLeft = offset.left;
var selfWidth = self.width();
var selfHeight = self.height();
$(element).css({
top: selfTop,
left: selfLeft,
width : selfWidth,
height : selfHeight
});
}
$(document).mousemove(function(ev){
$("#mouseTracking").position({
my: "left bottom",
of: ev,
offset: "3 -3",
collision: "fit"
});
});
var timedShort = function() {
$('#resizer').html("Really short").resize();
setTimeout(timedLong, 10000);
}
var timedLong = function() {
$('#resizer').html("Really longggggggggggggggggggggggggggggggggggggggggggggggggggg text").resize();
setTimeout(timedShort, 10000);
}
setTimeout(timedLong, 10000);
$("#elementOne").bind("reposition",
function() { repositionFunction(this, "#elementOneTracker"); });
$("#mouseTracking").bind("reposition",
function() { repositionFunction(this, "#mouseTrackingTracker"); });
$("#resizer").bind("reposition",
function() { repositionFunction(this, "#resizerTracker"); });
});
</script>
</head>
<body>
<div class="trackedDiv" id="mouseTracking">tracks mouse</div>
<div class="trackingDiv" id="mouseTrackingTracker"></div>
<div style="clear:both;"></div>
<div class="trackedDiv" id="resizer">resizer: resizes</div>
<div class="trackingDiv" id="resizerTracker"></div>
<div class="trackedDiv" id="elementOne">elementOne: floats to the right</div>
<div class="trackingDiv" id="elementOneTracker"></div>
</body>
</html>
You can fire custom events with jquery whenever you reposition the element.
$( window ).bind("resize",function(){
$("#elementOne").css({
top: 200,
left: 200
}).trigger("reposition");
});
// and now you can listen to a "reposition event"
$("#elementOne").bind("reposition",function(){
var self = $(this);
$("#elementTwo").css({
top: self.css("top"),
left: self.css("left")
});
});
So you can provide event hooks yourself with some manual coding, which is useful since cool events like DOMAttrModified and so on, are not fully supported in all browsers. The downside, you have to do it all yourself.
Unfortunately, there are no reliable events to tell you when an element moves or is resized. You could resort to polling the element, though that won't necessarily be the most performant solution:
setInterval(repositionElement, 10);
Another option is to make your element "track" the other element purely through CSS. For this to work, you'll need a "wrapper" around the element you're tracking, and the other element:
#wrapper-around-element-to-track
{
position: relative;
}
#tracked-element
{
position: absolute;
/* set top and left to position, if necessary */
}
#tracking-element
{
position: absolute;
/* set top and left to position, if necessary */
}
Since you're already using jQuery, you can also use the resize event plugin to simulate the resize event on any element, but if I recall the last time I looked at it, it simply does the polling like I mentioned.
There is the DOMAttrModified event, but its only impleneted in Firefox and Chrome. But as you need a JavaScript function to start the element moving, you can firing a custom event with Jquery in this place.
This function adds an overlay with the following properties to the entire browser screen,
$('a.cell').click(function() {
$('<div id = "overlay" />').appendTo('body').fadeIn("slow");
});
#overlay
{
background-color: black;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
display: none;
z-index: 100;
opacity: 0.5;
}
And this function is supposed to remove it.
$('#overlay').click(function() {
$(this).fadeOut("slow").remove();
});
But it seems to do absolutely nothing and now my page is stuck with a black overly over it. What's wrong with the removal?
The problem is that when you're adding the click handler, there isn't any overlay, so you're adding the handler to an empty set of elements.
To fix this, use the live method to bind your handler to all elements that match #overlay, whenever they are created.
Also, fadeOut is not a blocking call, so it returns before the element finishes fading out. Therefore, you're calling remove right after the element starts fading out.
To fix this, use fadeOut's callback parameter to call remove after the animation finishes.
For example:
$('#overlay').live(function() {
$(this).fadeOut("slow", function() { $(this).remove(); });
});
Here you go. This should fix the problem and let the overlay fade out before removing it.
$('#overlay').live("click", function() {
$(this).fadeOut("slow", function() { $(this).remove() });
});
Remove should be in the callback to fadeout, like so:
$('#overlay').live('click', function() {
$(this).fadeOut("slow", function() {
$(this).remove();
});
});
Try:
$('#overlay').live('click', function() {
$(this).fadeOut("slow").remove();
});
My recommendation is to use the jquery.tools overlay plugin. Your overlay will have a trigger (usually a button or link), but you can load or clear it with a javascript command, e.g.:
js:
var config = { closeOnClick:true, mask:{opacity:0.7, color:'#333', loadSpeed:1} }
$("#myTrigger").overlay(config); // add overlay functionality
$("#myTrigger").data("overlay").load(); // make overlay appear
$("#myTrigger").data("overlay").close(); // make overlay disappear
html:
<div id="myOverlay" style="display:none;">Be sure to set width and height css.</div>
<button id="myTrigger" rel="#myOverlay">show overlay</button>