I have a question regarding mouse events in the jQuery library.
I have a simple javascript function as following:
$(function() {
var xpos;
var ypos;
$("#pic1").mousedown(function() {
$("#pic1").mousemove(function(e) {
xpos = e.pageX;
ypos = e.pageY;
$("#pic1").css({'left': xpos, 'top': ypos});
});
});
});
It makes it so you can click an image and it follows the mouse around. I'm trying to make it stop following by using the mouseup function, but it seems like it can't break the "repaint" method, where it updates the css coordinates.
HTML:
<img id="pic1" src="img/test.jpg" alt="">
CSS:
#pic1 {
position: absolute;
}
Would there be an easier way to accomplish this?
The way you've set this up the mousemove trigger is bound on mouse down. To drop the element you would need to either unbind the trigger (http://api.jquery.com/unbind/) or set up a condition in the move handler so that the element's position is only updated if a condition is met and then make sure that mouse down/up turn that condition on/off. The former seems simpler but even simpler might be to use the jquery ui: http://jqueryui.com/draggable/
good luck
If you don't want to use the jquery ui draggable, your structure would look something like this:
$(function() {
$("#pic1").on('mousedown', function() {
$(this).on('mousemove', function(e) {
$(this).css({'left': e.pageX, 'top': e.pageY});
});
}).on('mouseup', function() {
$(this).off('mousemove');
});
});
Here's a little refactor using jQuery .on() and .off():
$(function() {
var xpos,
ypos,
$pic = $('#pic1');
$pic.on('mousedown', function() {
$pic.on('mousemove', function(e) {
xpos = e.pageX;
ypos = e.pageY;
$pic.css({'left': xpos, 'top': ypos});
});
});
$pic.on('mouseup',function(){
$pic.off('mousemove');
});
});
Demo: http://jsfiddle.net/tYpKL/1/
.off() is a pretty useful method that allows you to unbind methods set with .on().
I think you should consider using a library to handle this functionality because, as you can tell from the demo, you aren't even close to a solid user-experience. :)
Good luck!
There is a much easier solution.
HTML:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
#pic1 { width: 100px; height: 100px; padding: 1px; }
</style>
<script>
$(function() {
$("#pic1").draggable();
});
</script>
</head>
<body>
<div id="pic1" class="ui-widget-content">
<img src="pic1.jpg" alt="Image 1">
</div>
</body>
</html>
Here is a link (http://api.jqueryui.com/draggable/) that will explain all the details of the API used for the draggable function.
Related
currently im having a decent bit of trouble getting my jquery code to work. I'm trying to make the div load in with the correct background image but it doesnt wanna do so. I cant find out what might be wrong since im pretty new to jquery. I have a container set which needs a background image within the html attr 'srcpost' which contains something like
url("movies/Napoleon Dynamite/poster.jpg")
Ill post what I have so far, nothing happens on load. just a blank div with no background image :(.
$( '.video_selection' ).on( 'load', function() {
var backgroundimg = $( this ).attr('srcpost');
$( this ).css('background-image', backgroundimg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("movies/Napoleon Dynamite/poster.jpg")'>
<p>Napoleon Dynamite</p>
</div>
Please don't use element .onload method: Jquery on() load event on a single element. Might as well use $(document).ready(). Which would render your $(this) targeting window and you must change to element class. Also take care of \ in vidurl.
/*$(window).on( 'load', function() {
var backgroundimg = $('.video_selection').attr('srcpost');
console.log(backgroundimg); // << you can comment or delete this. only for demo purpose
$('.video_selection').css({'background-image': backgroundimg});
}); // window load will wait for all the content (images etc) to load before starting. */
$(document).ready(function(){
var backgroundimg = $('.video_selection').attr('srcpost');
console.log(backgroundimg); // << you can comment or delete this. only for demo purpose
$('.video_selection').css({'background-image': backgroundimg});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("movies/Napoleon Dynamite/poster.jpg")'>
<p>Napoleon Dynamite</p>
</div>
Also if you want to define multiple css value you can add them in {}:
$(document).ready(function(){
var backgroundimg = $('.video_selection').attr('srcpost');
$('.video_selection').css({'background-image': backgroundimg, 'height': '500px'});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500")'>
<p>Napoleon Dynamite</p>
</div>
$(function(){
var backgroundimg = $('.video_selection').attr('srcpost');
$( '.video_selection' ).css('background-image', backgroundimg);
})
.video_selection {
width: 500px;
height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg")'>
<p>Napoleon Dynamite</p>
</div>
You can do like this for trigger load event for div.
$(function(){
$('div[onload]').trigger('onload');
});
function changebackground(div) {
var backgroundimg = $('.video_selection').attr('srcpost');
//alert(backgroundimg)
$('.video_selection').css('background-image', backgroundimg);
}
$(function(){
$('div[onload]').trigger('onload');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='video_selection' onload="changebackground(this)" vidurl='movies\Napoleon Dynamite\napdyn.mp4' srcpost='url("https://cdn.pixabay.com/photo/2016/04/15/04/02/water-1330252__340.jpg")'>
<p>Napoleon Dynamite</p>
</div>
Hi guys I was making a javascript function for dismissing or hiding a div Ive search through the internet and found some answers but it does not apply on my code
Here is my code:
<script>
function Displayout()
{
$("#siteicon").mouseout(function () {
$("#map_tooltip").hide("drop", { direction: "down" }, "slow");
});
}
</script>
And here is the div that will trigger the function
<div id='siteicon' style="background-image:url('src/images/redbutton.png');margin-top:0px;margin-left:-8px;height:10px;width:10px;background-repeat:no-repeat;" onmouseover="displayData();" onmouseout="Displayout();"></div>
UPDATE:
and here is the id of the div I want to hide
<div id='infocontainer'></div>
Thank you in advance
Seems like there is syntax wrong with your hide() method. Try this:
function displayData()
{
$("#map_tooltip").show("slow");
}
function displayOut()
{
$("#map_tooltip").hide("slow");
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<div id='siteicon' style="background-color:grey;margin-top:0px;margin-left:-8px;height:20px;width:60px;background-repeat:no-repeat;" onmouseover="displayData();" onmouseout="displayOut();">SiteIcon</div>
<div id='map_tooltip' hidden="true">Should be hidden on mouseout of #siteicon</div>
The parameters for hide are wrong, it's giving error "Uncaught TypeError: n.easing[this.easing] is not a function". You can use "slow" to slow up the hiding effect but you can't specify the direction. You order is wrong as well. Please have a look at JSFiddle for Demo and api.jquery.com for for hide function.
You don't need onmouseout since you are using JQuery, and there seems to be a problem in the hide() of yours, so try removing the parameter inside.
$('#test').mouseout(function() {
$(this).hide();
})
#test {
height: 200px;
width: 200px;
background-color:pink}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">content</div>
Have a fairly simple show/hide script for a set of data filters from a button. I've been looking at solutions on how to animate the transition but can't seem to see how this script differs from what's described on the jQuery site.
I read somewhere else that CSS3 animations might be easier or better but that also remains a mystery to me.
Is there an easy modification to this script:
$('.toggle').click(function (event) {
event.preventDefault();
var target = $(this).attr('href');
$(target).toggleClass('hidden show');
});
Instead of changing the classes, you can use the built-in toggleX methods (eg toggle() and slideToggle()).
If you want to do something more fancy such as animating colours, you'll need to look at the animate method and possibly including jquery-ui, which is where css3 transitions may be easier / less overhead unless you're already including jquery-ui.
$("#toggle").click(function() {
$("#target").toggle(500);
});
$("#slide").click(function() {
$("#target").slideToggle(500);
});
Basic fiddle: https://jsfiddle.net/t2j03v6d/
$('.target').on( 'click', function () {
var $stuff = $(this).find('.stuff');
if ( $stuff.is(':visible') ) {
$stuff.slideUp('slow');
} else {
$stuff.slideDown('slow');
}
});
.target .stuff {
display: none;
height: 400px;
background-color: #F00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li class="target">
Show/Hide
<div class="stuff"></div>
</li>
</ul>
I'm not sure what animation you're looking for but here I've used slideToggle() (http://api.jquery.com/slidetoggle/) using some of the code you've provided: https://jsfiddle.net/8gavvmnL/1/
HTML:
<a class="toggle" href="#pop">Click Me</a>
<div id="pop">
I'm hidden until the button is clicked!
</div>
jQuery:
$("#pop").hide();
$('.toggle').click(function (event) {
event.preventDefault();
var target = $(this).attr('href');
$(target).slideToggle();
});
can anyone help me fix this, what am I missing?
<script type="text/javascript">
$('#loginButton').click(function() {
$('#toplogin').animate({
height: '0px'
});
});
</script>
The onClick doesn't even execute!
The div I want the onClick event to work on is here:
<div id="loginButton">Login »</div>
The div I want the animation to affect is here:
div id="toplogin"> <!-- more stuff --> </div>
Remove the semicolon after height: '0px' to make your JavaScript valid.
<script type="text/javascript">
$('#loginButton').click(function() {
$('#toplogin').animate({ height:'0px' });
});
</script>
However, unless you have overflow:hidden set for #toplogin the element will still be visible, even though it's height is 0px. An easier way is just using slideUp().
<script type="text/javascript">
$('#loginButton').click(function(){ $('#toplogin').slideUp(); });
</script>
try this:
$('#loginButton').click(function() {
$('#toplogin').animate({
height: 0
},
function() {
$(this).css('display', 'none');
});
});
you should wrap your code in following construction to make it valid as jQuery code:
$(document).ready(function(){
your code;
})
Hey there guys, Im good with HTML and CSS but have only jsut started to scratch the surface of jQuery. I'm looking to make 3 divs fade in on page load one after another.
So far I have this
<script type="text/javascript">
$('#1').hide().fadeIn(1500);
$('#2').hide().fadeIn(1500);
$('#3').hide().fadeIn(1500);
</script>
I heard that to use css to set the display to none is a nightmare for anyone with a non JavaScript browser so I used the hide function to initially hide the divs.
But this only fades them in all at once.
Any ideas?
You can .delay() each so the one before fades in at the right time, for example:
$("#1, #2, #3").hide().each(function(i) {
$(this).delay(i*1500).fadeIn(1500);
});
This fades them in...in the same order they occur in the page which is usually what you're after, the first is delayed 0 so it's instant, the second is delayed 1500ms (so when the first finishes, etc). In the .each() callback i is the index, starting with 0 so you can use that to quickly calculate the right delay here.
Another advantage here is this approach is much easier to maintain, give them a class for example then you can just do:
$(".fadeMe").hide().each(function(i) {
$(this).delay(i*1500).fadeIn(1500);
});
Then you require zero maintenance on the JavaScript side to add additional <div> elements to fade.
The fade in command contains a call back function, see documentation. This means you could chain the events.
<script type="text/javascript">
$('#1, #2, #3').hide();
$('#1').fadeIn(1500, function(){ $('#2').fadeIn(1500, function(){$('#2').fadeIn(1500)})});
</script>
<script type="text/javascript">
$('#1').hide().fadeIn(1500, function(){
$('#2').hide().fadeIn(1500, function(){
$('#3').hide().fadeIn(1500);
});
});
</script>
Using the Delay function as following:
<script type="text/javascript">
$('#1').hide().fadeIn(1500);
$('#2').hide().delay(1500).fadeIn(1500);
$('#3').hide().delay(3000).fadeIn(1500);
</script>
Here is a cleaner and generic way to achieve this effect:
check it out on http://jsfiddle.net/BztLx/20/
Logic trick relies on the callback functionality of the fadeIn and using .eq() as an iterator over the selected elements.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function sequentialFadeIn(selectorText, speed, display, callBack) {
display = typeof display !== 'undefined' ? display : "block";
var els = $(selectorText), i = 0;
(function helper() {
els.eq(i++).fadeIn(speed, helper).css("display", display);
if (callback && i === els.length) callback();
})();
}
sequentialFadeIn(".toBeFaddedIn", "slow", "inline-block", function() {
console.log("I am just an optional callback");
});
});
</script>
</head>
<body><style media="screen" type="text/css">
.hello {
background-color: blue;
height:50px;
width: 50px;
display: none;
}
</style>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
</body></html>