HTML elements touched each other [duplicate] - javascript

This question already has answers here:
jQuery/JavaScript collision detection
(7 answers)
Closed 8 years ago.
I have a button, and two HTML elements. After pressing the button, i called animate function from j query to start moving the first element to right and let two HTML elements get touched.
How i will detect that two HTML elements get touched?
Need Help. Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").animate({
left:'250px',
});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<div id = "div1" style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div>
<div id = "div2" style="background:#98bf21;height:100px;width:100px;position:absolute;left:50%;right:50%">
</div>
</body>
</html>

Your elements won't ever touch, because your selector $('div') which you are animating will animate both divs and move them both by the same amount. They will end up the same distance apart.
Also, you can't use <div2> as a tag name. Instead, use an id attribute to assign them a unique name, like this:
<div id="div1"></div>
<div id="div2"></div>
Then instead of animating $('div'), animate $('#div1').
You can first get the `left` position of `#div2` in pixels and use that value to animate the `right` position of `#div1` to exactly that spot, like this:
$(document).ready(function(){
// when the buttom is clicked
$('button').click(function(){
// get the left position of div2
var div2Left = $('#div2').position().left
// animate so that the right side of div1 matches div2's left
$('#div1').animate({
'right': div2Left + 'px',
});
});
});
--EDIT--
I misread your question, I thought you were asking how to get them to touch. If you want to detect that they have overlapped, you can use the step function of the animation to check if the right side of div1 crosses the left side of div2. Try this:
$(document).ready(function(){
// when the buttom is clicked
$('button').click(function(){
// get the left position of div2
var div2Left = $('#div2').position().left
// animate so that the right side of div1 matches div2's left
$('#div1').animate({
'right': '250px',
}, {
// this is called every step of the animation
step: function(currentRightPos) {
// check if collision occurs
if (currentRightPos >= div2Left) {
console.log('The divs collided!');
}
}
});
});
});

Related

Change Mouse cursor according to X/Y position

Is there a simple cross-browser css3 solution to altering the mouse cursor to a clear right/ left graphic according to the mouse position within a div? Or is this a JQuery plugin job?
As in the mouse reaction in the carousel area in this http://themeforest.net/item/flamingo-agency-freelance-portfolio-theme/full_screen_preview/6077145
You can use the :hover selector with the cursor property to do this. Make two fixed, transparent elements for each half of the page to use with :hover, and specify a custom cursor image by assigning cursor a URL. No JS required...
With JS programatically make a div follow the hidden cursor.
See example:
<div class="main_area">
...
...
...
</div>
<!--
// The html:
-->
<div id="custom_cursor">HELLO</div>
<!--
// The script uses jQuery
-->
<script type="text/javascript">
$(document).ready(function(){
var $area = $('.main_area').css({
'cursor':'none'
}),
$myCursor = $('.custom_cursor').css({
'position': 'fixed',
'z-index': '999'
})
if ($myCursor.lenght){
$area
.on('mouseout.customCursor', function(){
$myCursor.hide()
})
.on('mousemove.customCursor', function(event){
$myCursor.show().css({
'left': event.clientX - 20,
'top': event.clientY + 7
})
})
}
});
</script>

Move div on click

I really can't do a little thing. I want that div1 change it's position ON CLICK of div2 (note that div2 is inside of div1) and when clicking again div2, put div 1 to his original position. (If you could help me moving the div1 with a little animation it would be perfect).
I added my exemple to jsfiddle, where I want to change the "switcher"'s position on first click on "switcher-header", and when click second time "switcher-header" take "switcher" back to it's original position.
http://jsfiddle.net/mdx7dpeL/3/
You could have a variable to toggle the marginLeft, so one click you animate left, and the other click you animate right:
var switched = false;
$(document).ready(function() {
$('.switcher-header').click(function() {
var marginLeft = switched ? '-30px' : '30px';
switched = !switched;
$('#switcher').animate({
'marginLeft' : "+=" + marginLeft //moves right
});
});
});
and of course you need to include jQuery.
Fiddle

Dragging a div out from underneath multiple other divs

I have been trying to create a test case for a webapplication we are making and I am quite close to a solution, but the final part has me stumped...
We need to be able to drag divs around (no problem there), but some of the divs need to be locked in place (again, no problem).
The problem arises when a draggable div is stuck underneath a non draggable div. I have fixed this somewhat, but it only works if there is only ONE non draggable div on top of the draggable one.The moment it overlaps with another non draggable div, it won't work. Which is weird, as I am correctly accessing the draggable div.
my HTML:
<body>
<div id="div1" class="draggable"></div>
<div id="div2" class="locked"></div>
<div id="div3" class="locked"></div>
</body>
And here is my javascript:
<script>
$(document).ready(function () {
$(document).mousemove(function (e) {
window.mouseXPos = e.pageX;
window.mouseYPos = e.pageY;
});
});
$(function () {
$(".draggable").draggable();
});
$('.locked').ready(function () {
$('.locked').mousedown(function (e) {
var layer = e.target;
$("#data").html($("#data").html() + " " + layer.id);
$(layer).addClass("hide");
var lowerLayer = document.elementFromPoint(window.mouseXPos, window.mouseYPos);
if ($(lowerLayer).hasClass("locked")) {
$(lowerLayer).mousedown();
}
else if ($(lowerLayer).hasClass("draggable")) {
$("#data").html($("#data").html() + " " + lowerLayer.id);
$(lowerLayer).trigger(e);
}
$(layer).removeClass("hide");
});
});
</script>
Okay, so the idea is this, I use jquery to set everything with the class "draggable" to be able to be dragged. The body gets a mousemove event to store the current mouse position. While all the elements with the "locked" class, will fire a mousedown event. In this event, I hide the element I am clicking on by adding a class called "hide" (which contains only a display: none).
At this point, the element underneath the clicked element is visible. Using the elementFromPoint combined with my stored mouse positions, I grab the lower element.
By then checking if it is "locked" or "draggable" I can determine what this element should do. If it's locked, I force it to execute a mousedown event. If it's draggable, I use the .trigger(e) to start dragging.
I then remove the "hide" class again, so that the element does not stay hidden.
Using the div called data, I can see that the function does indeed reach the draggable div. However, if both locked divs are on top of it, it will not start dragging. If there is only one locked div on top, I can then start dragging the draggable div.
In my opinion, this should work without any problems. I mean, it works with only 1 overlapping div, and even with 2 (or more), I am still triggering the code in the else if statement.
What am I missing/overlooking?
-Ferdy
I rewrote your script slightly differently and it seems to work. The problem might be that you're using e.target, but i'm not really sure. Here's what i did:
$(".draggable").draggable();
$(".locked").mousedown(function(e) {
var layer = $(this);
layer.addClass("hide");
var lowerLayer = $(document.elementFromPoint(e.pageX, e.pageY));
if (lowerLayer.hasClass("draggable") || lowerLayer.hasClass("locked"))
lowerLayer.trigger(e);
layer.removeClass("hide");
});
http://jsfiddle.net/AXycq/

Make javascript happen in real time

I have made a circle from a div with rounded borders. I have made this div draggable using jquery ui. I would like to know how to make it so that the further to the left you drag the div the less opacity it has. Heres a snippet of what i have coded already:
<script type="text/javascript" language="javascript">
$(function() {
$( "#circle" ).draggable();
});
var circ = document.getElementById('circle');
var num = circ.style.left/1000;
</script>
</head>
<body>
<div id="circle"></div>
<script type="text/javascript">circ.style.opacity = num;</script>
</body>
</html>
I know i can get this to work by putting the circ.style.opacity = num; into a function and calling that function but i was wondering if there was a way for it to just automatically change?
Thanks for your help.
As others have already suggested, simply calculate your opacity in the drag callback and set the opacity. The drag callback is called continously until the drag stops. This is how the "live" update works.
Example:
$('#circle').draggable({
"drag": function (e, ui) {
var percentOpacity = someVal; //compute this however you like
$(this).css('opacity', percentOpacity);
}
});
Working Demo: http://jsfiddle.net/gzA8w/
In the working demo, I am simply calculating the opacity as a function of how many pixels the element is from the right edge of the document. The further left you go, the more transparent it gets.

Scroll to left-most element on window resize - how?

I'm a bit of a jQuery newbie, only recently started.
I am using http://flesler.blogspot.com.au/2007/10/jqueryscrollto.html (Ariel Flesler's scrollTo plugin)
it's a horizontal scrolling website.
I'm trying to scroll to the element which is closest to the left side of the window when the window gets resized.
I can only seem to be able to get it to scroll to the first element in the array, so when I resize the window, no matter where the window is, the window scrolls to the first ".example" in the flow.
Update: I've made some progress, I've added a new variable to calculate how far has been scrolled. now i seem to need a way to find out what the lowest value of the loop is to use in my "if" statement as it seems to want to jump from one element to the next or none at all.
the "Uncaught TypeError: Cannot read property 'slice' of undefined was due to the value of the scrollTo being negative (you can't scroll below 0 as 0 is the beginning of your document) so to fix this i added the value of how much has been scrolled so far, and then added whatever value element_position had to calculate correctly.
Update 2: there was a problem with my mathematics, the question has been updated to reflect the solution. only problem now is that it's a fluid layout, so using fixed values like "70" in my if statement tend to break it after a certain point.
jQuery
$(document).ready(function(){
$(window).resize(function() {
$('.example').each(function(index) {
var example = $(this);
var scroll_position = $('#container').scrollLeft();
var element_position = example.offset().left;
if (element_position < 70 && position > -70) {
$('#container').scrollTo(scroll_position + element_position);
}
});
});
});
HTML
<div id="container">
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
</div>
I also recieve the following error
"Uncaught TypeError: Cannot read property 'slice' of undefined
try this one:
$(document).ready(function(){
$(window).resize(function() {
var scroll_position = $('#container').scrollLeft();
$('.example').each(function() {
var example = $(this);
var left = example.offset().left;
var right = left + example.width();
if (right > 0) {
$('#container').scrollTo(scroll_position + left);
return false;
}
});
});
});​
checks for the first element in the selected elements that has its right border in the viewport..

Categories