I am following this guide: http://draggabilly.desandro.com/
which I think is hard to understand and I can't seem to figure out what to add to track the positions of the elements I drag around. If you look on the site, you can see the last example where they do it. My example so far is this:
<div id="house_wall1">
<img src="xxx" class="draggie" style="position:relative;">
<img src="xxx" class="draggie" style="position:relative;">
<img src="xxx" class="draggie" style="position:relative;">
<!--Cypyrights and many thanks to http://desandro.mit-license.org for element movements -->
<?php if (login_check($mysqli) == true) : ?>
<p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
<?php
echo $username;
?>
</div>
<script type="text/javascript" src="draggabilly.pkgd.min.js"></script>
<script>
( function() {
var container = document.querySelector('#house_wall1');
var elems = container.querySelectorAll('.draggie');
for ( var i=0, len = elems.length; i < len; i++ ) {
var elem = elems[i];
new Draggabilly( elem, {
containment: true
});
}
})();
function onDragMove( instance, event, pointer ) {
console.log( 'dragMove on ' + event.type +
pointer.pageX + ', ' + pointer.pageY +
' position at ' + instance.position.x + ', ' + instance.position.y );
}
// bind event listener
draggie.on( 'dragMove', onDragMove );
// un-bind event listener
draggie.off( 'dragMove', onDragMove );
// return true to trigger an event listener just once
draggie.once( 'dragMove', function() {
console.log('Draggabilly did move, just once');
});
This script makes it possible to move the images around but it does not track their positions yet even though I have tried adding it at the bottom of the script as you can see. Does anybody have an idea what can be wrong or whats needed? I'm fairly new at Jquery, Javascript. Many thanks.
Change your code to this, Works fine for me. You just need to use offset() methods to get the position of dragged element when it is getting dragged and position() method to get the co ordinates of the position where it got dropped.
HTML:
//include these files.
<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/jquery-2.0.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<body>
<div id="container">
<img id="productid_1" src="Lionel Messi New Wallpaper 2012 07.jpg" class="item" alt="" title="" height="100px" width="100px"/>
<img id="productid_2" src="bienvenidos_a_uniformes_deportivos_monterrey_4_216235520.jpg" class="item" alt="" title="" height="100px" width="100px" />
<img id="productid_3" src="lionel-messi-wallpapers-hd.jpg" class="item" alt="" title="" height="100px" width="100px"/>
<?php if (login_check($mysqli) == true) : ?>
<p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
<?php
echo $username;
?>
</div>
<div id="start">Waiting for dragging the image get started...</div>
<div id="stop">Waiting image getting dropped...</div>
<ul>
<li id="posX"></li>
<li id="posY"></li>
</ul>
</body>
JQUERY:
<script>
$(document).ready(function(){
$(".item").draggable({
drag: function(){
var offset = $(this).offset();
var xPos = offset.left;
var yPos = offset.top;
$('#posX').text('x: ' + xPos);
$('#posY').text('y: ' + yPos);
},
// Find original position of dragged image.
start: function(event, ui) {
// Show start dragged position of image.
var Startpos = $(this).position();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
},
// Find position where image is dropped.
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
}
});
});
</script>
EDIT:
$(document).ready(function(){
$(".item").draggable({
containment: '#limit_div',
drag:function(){......
//where #limit_div will be parent div of the #container div.
Related
Confused why this happened,
when I am in second page (ex: product_detail.html?id=1), then I want to click the same page but different id (ex :product_detail.html?id=5) it is not working, nothing displayed.
Here is my index.html
<script type="text/javascript" src="cordova.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.mobile.min.js"></script>
<div class="item">
<img src="http://web/banner2.jpg">
</div>
<div class="item">
<img src="http://web/banner3.jpg">
</div>
<script>
$( document ).on( "pageinit", "#detailsPage", function( event ) {
var parameters = $(this).data("url").split("?")[1];
parameter = parameters.replace("id=","");
var devid=localStorage.getItem("macid");
$.getJSON('http://url_web_services/related_product.php?id='+parameter, product_detail);
});
function product_detail(data) {
var employee = data.item;
var urls="";
urls="http://url_web_services/"+employee.product_image;
var myid3="";
myid3 = localStorage.getItem("macid");
$('#product_detail').append('<a href="product_detail.html?id='+employee.product_id+'"><div class="item">');
$('#product_detail').append('<div class="xxw"><img src="http://webservice' + employee.promo_image +'"></div>');
$('#product_detail').append('<div style="background-color:#2E64FE;margin-top:15px;"><font color="#FFFFFF" face="arial" size="3">' + employee.product_name + '</font></div><br>');
$('#product_detail').append('</div></a>');
//SIMILAR PRODUCT
var idp=employee.promo_id;
$.getJSON('http://webservice/product_related.php?id='+idp, function(data) {
employees2 = data.items;
$.each(employees2, function(index, employee2) {
$('#product_similar').append('<a href="product_detail.html?id='+employee2.product_id+'"><div class="some">'+
'<div><img src="http://webservice/' + employee2.product_image +'" class="bgr"></div>'+
'<div class="four"><p style="margin-left:5px;margin-top:2px;"><font face="arial" size="2" color="black"><b>'+employee2.product_name+' ....</b></font></p></div>'+
'</div></a>');
});
});
}
</script>
here is my second page product_detail.html
<div data-role="page" id="detailsPage">
<div data-role="header" data-tap-toggle="false" data-theme='b'>
<h1 class="header-title">Detail</h1>
</div>
<div data-role="content" id="product_detail">
</div>
<br>
<div style="background-color:#3104B4;margin-top:5px;"><font color="#FFFFFF" face="arial" size="3"><center>PRODUCT SIMILAR</center></font></div>
<div id="product_similar" style="background-color:#E6E6E6;margin-top:2px;">
</div>
<div data-role="footer" data-theme="none" data-inner="true" data-border="false">
</div>
</div>
when I click one of item in product_similiar (it means reload the same page, but different ID, it displays nothing)
You can try dynamically creating page with the new values, here is an example:
<img src="http://web/banner2.jpg">
<script>
function create_page(page_id) {
var jsonUrl = 'http://url_web_services/related_product.php?id=' + page_id
var content = $('#detailsPage').html();
var newPage = '<div data-role="page" id="product_detail_id=' + page_id + '">' + content + '</div>'
$('body').append(newPage);
//initialize the new page
$.mobile.initializePage();
//navigate to the new page
$.mobile.changePage("#product_detail_id=" + page_id, "pop", false, true);
//now you can get #product_detail
$.getJSON(jsonUrl , product_detail);
}
</script>
With some adjustments it should work
I have drag-and-drop items, intended to be dragged from one div and dropped into another div. I capture the original position of each item in hidden fields when they are created.
I want to get the items to go back to the original div and location on dblclick, but they always relocate inside the drop target div.
Any ideas?
<div id="cardPiles">
<div id="D1" class="draggable" ondblclick="rev(this)">1</div>
<div id="D2" class="draggable" ondblclick="rev(this)">2</div>
<div id="D3" class="draggable" ondblclick="rev(this)">3</div>
<div id="D4" class="draggable" ondblclick="rev(this)">4</div>
<div id="D5" class="draggable" ondblclick="rev(this)">5</div>
<div id="D6" class="draggable" ondblclick="rev(this)">6</div>
</div>
function rev(me) {
var b = $(me).text();
var h = $('#H' + b).text();
var s = h.split(',');
var top = s[0];
var left =s[1];
$(me).parent().css({ position: 'relative' }); //tried absolute also
$(me).css({top:top,left:left,position:'absolute' });
}
Here is a possible answer. If it does not fit your use case, edit your post with more details.
Working Example: https://jsfiddle.net/Twisty/u1rd9dpg/6/
HTML
<div id="cardPiles">
<div id="D1" class="draggable ui-widget-content" data-origin="">1</div>
<div id="D2" class="draggable ui-widget-content" data-origin="">2</div>
<div id="D3" class="draggable ui-widget-content" data-origin="">3</div>
<div id="D4" class="draggable ui-widget-content" data-origin="">4</div>
<div id="D5" class="draggable ui-widget-content" data-origin="">5</div>
<div id="D6" class="draggable ui-widget-content" data-origin="">6</div>
</div>
<div id="cardDrop">
</div>
JQuery
function rev(me) {
console.log("DoubleClick Detected.");
var pos = me.data("origin");
console.log("Returning to: ", pos);
var $o = me.clone();
$o.draggable({
cursor: "move",
start: log
});
me.remove();
if ($("#cardPiles div").length == 0) {
$("#cardPiles").append($o);
return true;
}
$("#cardPiles .draggable").each(function(k, v) {
var txt = parseInt($(v).text());
if ($o.data("order") < txt) {
$(v).before($o);
return false;
} else {
$("#cardPiles").append($o);
}
});
}
function log(e, ui) {
var pos = ui.offset;
var $ob = $("#" + ui.helper.attr("id"));
pos.order = parseInt(ui.helper.text());
$ob.attr("data-top", pos.top);
$ob.attr("data-left", pos.left);
$ob.attr("data-order", pos.order);
$ob.attr("data-origin", [pos.top, pos.left, pos.order].join(","));
console.log("DragStart Position: ", pos);
console.log("Logged: " + [$ob.data("top"), $ob.data("left"), $ob.data("order")].join(","));
}
$(function() {
$(".draggable").draggable({
cursor: "move",
start: log
});
$("#cardDrop").on("dblclick", ".dropped", function() {
console.log("Origin found: ", $(this).data("origin"), $(this).data("top"));
rev($(this));
});
$("#cardDrop").droppable({
accept: "#cardPiles div",
activeClass: "ui-state-highlight",
drop: function(e, ui) {
var $drop = ui.draggable.clone();
console.log("Dropped. Origin: ", $drop.data("origin"));
$drop.removeAttr("style");
$drop.addClass("dropped");
$(this).append($drop);
ui.draggable.remove();
var c = $("#cardDrop div").length;
}
}).sortable({
revert: true
});
});
I'm not sure if you need to do this in CSS or not, but I went based on the order and let the CSS just define how they appear in the list.
When the drag starts, I log the origin details to various data attributes. This allows them to be retrieved later when there is an interaction with just that element.
When drop happens, I clone the original and then append the clone. Do not have to do this, yet for me, it helps me identify whats happening. Since it's no longer draggable, you could remove the class, but I just added dropped to be able to more easily catch the Double Click event.
When dblclick fires on our object, I clone it again, and re-append it back. Make it .draggable() again too. I hunt for the next item's number and fit it in underneath.
If the text within is not easy to order like that, I would add an order attribute or populate the data-order attribute. You can do this when it's dragged or read it from the ID... not sure what might work best for you.
You can do this over and over and drag all of them out of #cardPile if you like.
I need to add a jQuery slider to my website and I found this one met my requirement. But the slider just show 3 pictures, how to add one or two other pictures to the slider?
Demo: http://d.lanrentuku.com/down/js/jiaodiantu-883/
The html code
<div id="preview-slider">
<div id="preview-slide-1" style="display: none;"><a target="_blank" href="http://www.lanrentuku.com/"><img width="930" height="300" alt="" src="images/01.jpg"></a></div>
<div class="preview-hide" id="preview-slide-2" style="display: block;"><a target="_blank" href="http://www.lanrentuku.com/"><img width="930" height="300" alt="" src="images/02.jpg"></a></div>
<div class="preview-hide" id="preview-slide-3" style="display: none;"><a target="_blank" href="http://www.lanrentuku.com/"><img width="930" height="300" alt="" src="images/03.jpg"></a></div>
<div id="preview-slider-line">
<ul id="preview-slider-holder">
<li class="preview-first">
<div class="preview-slider-thumbnail"><a target="_blank" href="http://www.lanrentuku.com/"><img width="66" height="36" id="preview-thumbnail-im1" alt="" src="images/01.png" style="top: 0px;"></a></div>
<span><a target="_blank" href="http://www.lanrentuku.com/">Picture 1</a></span></li>
<li class="preview-second">
<div class="preview-slider-thumbnail"><a target="_blank" href="http://www.lanrentuku.com/"><img width="66" height="36" id="preview-thumbnail-im2" alt="" src="images/02.png" style="top: -15px;"></a></div>
<span><a target="_blank" href="http://www.lanrentuku.com/">Picture 2</a></span></li>
<li class="preview-third">
<div class="preview-slider-thumbnail"><a target="_blank" href="http://www.lanrentuku.com/"><img width="66" height="36" id="preview-thumbnail-im3" alt="" src="images/03.png" style="top: 0px;"></a></div>
<span><a target="_blank" href="http://www.lanrentuku.com/">Picture 3</a></span></li>
</ul>
</div>
</div>
The javascript code
(function($){
$(document).ready(function() {
var ready = true, position = 1, timer = null, domer = $('ul#preview-slider-holder > li');
var anima = function () {
if (!ready) {
$("#preview-slider > div:not(':last'):not(':eq(" + position + ")')").each(function(){
if($(this).is(':animated')){
$(this).stop(true, true);
}
});
}
ready = false;
$("#preview-slider > div:not(':last'):not(':eq(" + position + ")')").hide();
$('img', this).animate({"top": "-15px"}, 200);
$('#preview-slide-' + (position + 1)).fadeIn(600, function(){
ready = true;
});
$('img[id^="preview-thumbnail-im"]:not([id="preview-thumbnail-im' + (position+1) + '"])').stop(true, false).animate({'top': '0px'}, 200);
position = ++ position % 3;
};
timer = setInterval(function(){anima.apply(domer)}, 2000); // interval time
domer.mouseover(function () {
timer == null || clearInterval(timer);
if($(this).hasClass('preview-first')){
position = 0;
} else if($(this).hasClass('preview-second')){
position = 1;
} else if($(this).hasClass('preview-third')){
position = 2;
}
anima.apply(this);
});
domer.mouseout(function () {
timer = setInterval(function(){anima.apply(domer)}, 2000);
});
});
})(jQuery);
I tried to add a li element , but it didn't work. I think I need to modify the javascript code. But I am not good at the programming, will someone tell how to do?
While I agree with DevlshOne, that many other quality sliders are out there. To answer the OP's question, you have to fix the code to not have hard-coded positions. Instead, I chose to use the index method present with jQuery.
Here is the jsFiddle that shows 4 images working (though I used the original code, so no actual images are displayed).
http://jsfiddle.net/a5yqx/
The key changes to the code are from:
position = ++ position % 3;
...
if($(this).hasClass('preview-first')){
position = 0;
} else if($(this).hasClass('preview-second')){
position = 1;
} else if($(this).hasClass('preview-third')){
position = 2;
}
To:
position = ++position % domer.length;
...
position = $(this).index();
Since I don't have the CSS to accompany it, I'm not sure what else you'll need to keep your style up, but good luck.
Last note, I changed the image size from your default to 10x10 in order to see it on my screen in the fiddle.
SOLUTION: I figured it out. I used jQuery instead of JavaScript with a little help from zohodiscussions.com.
Ajax Google plugin: http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
**js. file:**
function form_input_classes() {
jQuery('input[type="text"]').addClass('text');
jQuery('input[type="password"]').addClass('text');
jQuery('input[type="checkbox"]').addClass('checkbox');
jQuery('input[type="radio"]').addClass('radiobutton');
jQuery('input[type="submit"]').addClass('submit');
jQuery('input[type="image"]').addClass('buttonImage');
}
function form_labelize() { jQuery(".labelize input:text").clearingInput(); }
var version = jQuery.browser.version;
if (version instanceof Object) { version = version.number(); }
function loadXMLDoc(XMLname) {
return jQuery.ajax({ async: false, url: XMLname }).responseXML;
}
xmlDoc = loadXMLDoc("demo.xml");
var M = xmlDoc.getElementsByTagName("rotatingImages");
jQuery(function () {
jQuery('script').remove()
form_input_classes();
form_labelize();
var pauseClicked = function () {
jQuery('#cycle').cycle('pause');
jQuery('#play').attr("style", "display:block");
jQuery('#pause').attr("style", "display:none");
jQuery('#pause').removeClass("active");
return false;
};
var playClicked = function () {
jQuery('#cycle').cycle('resume');
jQuery('#pause').attr("style", "display:block");
jQuery('#play').attr("style", "display:none");
jQuery('#pause').addClass("active");
return false;
};
jQuery('#play').attr("style", "display:none");
jQuery('#pause').attr("style", "display:block");
jQuery('#pause').click(pauseClicked);
jQuery('#play').click(playClicked);
jQuery("#slideNavigation a").focus(function () {
jQuery(this).blur();
});
jQuery('#cycle').cycle({
fx: 'fade',
speed: 1000,
timeout: 5000,
prev: '#prev',
next: '#next',
pager: '#hero-nav ul ',
pagerAnchorBuilder: function (idx, slide) {
return '#hero-nav li:eq(' + idx + ') a.page';
}
});
})
**HTML references:**
<div id="content" class="clearfix home">
<div id="hero">
<div id='rotator'>
<div id='cycle' class='clearfix'>
<script type="text/javascript">
jQuery(M).find('image').each(function (i, img) {
document.write("<img src='" + jQuery(img).text() + "' />");
})
</script>
</div>
</div>
<!--end-rotating-images-->
<div id="hero-cycle" class="clearfix">
<div id="hero-nav">
<ul>
<script type="text/javascript">
jQuery(M).each(function (i, item){
document.write("<li class='hero-text'>");
document.write("<div class='hero-info clearfix'>");
document.write("<a href='" +
jQuery(item).find('filePath').text() + "' target='_blank'>" +
jQuery(item).find('description').text()
+ "</a>");
document.write("</div>")
document.write("<a class='page' href='#'></a></li>")
})
</script>
</ul>
<div id="annc_controls">
<a href="#" id="play">
<img src="images/blue_play.gif" alt="Play" border="0" style="vertical-align: text-bottom"/></a>
<a href="#" id="pause">
<img src="images/blue_pause.gif" alt="Stop" border="0" style="vertical-align: text-bottom"/>
</a>
</div>
<!--<div id="slideNavigation"></div>-->
</div>
<!-- /#hero-nav -->
</div>
<!-- /#hero-cycle -->
</div>
<!-- /#hero -->
</div>
I updated my code and the rotating images are inline with the description. The only problem I have is the javascript loads first in place of a 1st image. There are only 3 images and the code displays firs then image #1 and so on. Is this a browser issue with ActiveXObject and IE 9? I'm having a similar issue with FireFox latest version. Nothing shows in this browser. Any help? –
.html file:
<head><script type="text/javascript">
<!--
function loadXMLDoc(XMLname)
//
{
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", XMLname, false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
xmlDoc = loadXMLDoc("demo.xml");
var M = xmlDoc.getElementsByTagName("rotatingImages");
//-->
</script>
</head>
<div id="hero">
<div id='rotator'>
<div id='cycle' class='clearfix'>
<script type="text/javascript">
for (i = 0; i < M.length; i++) {
document.write("<img src='" + xmlDoc.getElementsByTagName("image")[i].childNodes[0].nodeValue + "' />");
}
</script>
</div>
</div>
</div>
<!--end-rotating-images-->
<div id="hero-cycle" class="clearfix">
<div id="hero-nav">
<ul>
<script type="text/javascript">
for (i = 0; i < x.length; i++) { // Start 3 Rotating Images
document.write("<li class='hero-text'>");
document.write("<div class='hero-info clearfix'>");
var linkValue = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
var linkValue = x[i].getElementsByTagName("filePath")[0].childNodes[0].nodeValue;
document.write("<a href='" + linkValue + "' target='_blank'>");
linkValue = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
document.write(linkValue);
document.write("</a>");
// End description for Rotating Images
document.write("</div>");
document.write("<a class='page' href='#'></a></li>");
}
</script>
</ul>
<div id="annc_controls">
<a href="#" id="play">
<img src="images/blue_play.gif" alt="Play" border="0" style="vertical-align: text-bottom" /></a>
<a href="#" id="pause">
<img src="images/blue_pause.gif" alt="Stop" border="0" style="vertical-align: text-bottom" />
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div>
XML file:
`<?xml version="1.0" encoding="utf-8"?>
<homepage>
<rotatingImages>
<item>
<image>manage/newImages/soldier-sunset.jpg</image>
<description>My Test 1</description>
<filePath>http://www.sigar.mil/newsroom/spotlight/12/2012-sep-05-sopko-visits-afghanistan.html </filePath>
</item>
<item>
<image>manage/newImages/2012-04-03-jet.jpg</image>
<description>My Test3</description>
<filePath>http://www.sigar.mil/newsroom/spotlight/12/2012-sep-05-sopko-visits-afghanistan.html </filePath>
</item>
<item>
<image>manage/newImages/sigar-brochre.jpg</image>
<description>My Test2 </description>
<filePath>http://www.sigar.mil/newsroom/spotlight/12/2012-sep-05-sopko-visits-afghanistan.html </filePath>
</item>
</rotatingImages>
</homepage>`
Since rotator and cycle elements are added dynamically, they don't exist when the page loads and the jQuery function runs. You need to delegate with .on() so that the handlers will be added when the elements are. For information on .on, see http://api.jquery.com/on/ and scroll down to the section on Direct and delegated events.
Another problem with your page is that you use the same ID each time through the for-loop. IDs have to be unique. The repeated IDs are coming from this code:
for (i = 0; i < x.length; i++) {
document.write("<div id='rotator'><div id='cycle' class='clearfix'><div class='entry clearfix'>");
Each time through the loop it adds DIVs with IDs 'rotator', 'cycle', 'hero-cycle', and 'hero-nav'.
Put the jQuery('#cycle').cycle({ … }); code into the jQuery(document).ready function.
**SOLUTION:** I figured it out. I used jQuery instead of JavaScript with a little help from zohodiscussions.com.
Ajax Google plugin: http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
**js. file:**
function form_input_classes() {
jQuery('input[type="text"]').addClass('text');
jQuery('input[type="password"]').addClass('text');
jQuery('input[type="checkbox"]').addClass('checkbox');
jQuery('input[type="radio"]').addClass('radiobutton');
jQuery('input[type="submit"]').addClass('submit');
jQuery('input[type="image"]').addClass('buttonImage');
}
function form_labelize() { jQuery(".labelize input:text").clearingInput(); }
var version = jQuery.browser.version;
if (version instanceof Object) { version = version.number(); }
function loadXMLDoc(XMLname) {
return jQuery.ajax({ async: false, url: XMLname }).responseXML;
}
xmlDoc = loadXMLDoc("demo.xml");
var M = xmlDoc.getElementsByTagName("rotatingImages");
jQuery(function () {
jQuery('script').remove()
form_input_classes();
form_labelize();
var pauseClicked = function () {
jQuery('#cycle').cycle('pause');
jQuery('#play').attr("style", "display:block");
jQuery('#pause').attr("style", "display:none");
jQuery('#pause').removeClass("active");
return false;
};
var playClicked = function () {
jQuery('#cycle').cycle('resume');
jQuery('#pause').attr("style", "display:block");
jQuery('#play').attr("style", "display:none");
jQuery('#pause').addClass("active");
return false;
};
jQuery('#play').attr("style", "display:none");
jQuery('#pause').attr("style", "display:block");
jQuery('#pause').click(pauseClicked);
jQuery('#play').click(playClicked);
jQuery("#slideNavigation a").focus(function () {
jQuery(this).blur();
});
jQuery('#cycle').cycle({
fx: 'fade',
speed: 1000,
timeout: 5000,
prev: '#prev',
next: '#next',
pager: '#hero-nav ul ',
pagerAnchorBuilder: function (idx, slide) {
return '#hero-nav li:eq(' + idx + ') a.page';
}
});
})
**HTML references:**
<div id="content" class="clearfix home">
<div id="hero">
<div id='rotator'>
<div id='cycle' class='clearfix'>
<script type="text/javascript">
jQuery(M).find('image').each(function (i, img) {
document.write("<img src='" + jQuery(img).text() + "' />");
})
</script>
</div>
</div>
<!--end-rotating-images-->
<div id="hero-cycle" class="clearfix">
<div id="hero-nav">
<ul>
<script type="text/javascript">
jQuery(M).each(function (i, item){
document.write("<li class='hero-text'>");
document.write("<div class='hero-info clearfix'>");
document.write("<a href='" +
jQuery(item).find('filePath').text() + "' target='_blank'>" +
jQuery(item).find('description').text()
+ "</a>");
document.write("</div>")
document.write("<a class='page' href='#'></a></li>")
})
</script>
</ul>
<div id="annc_controls">
<a href="#" id="play">
<img src="images/blue_play.gif" alt="Play" border="0" style="vertical-align: text-bottom"/></a>
<a href="#" id="pause">
<img src="images/blue_pause.gif" alt="Stop" border="0" style="vertical-align: text-bottom"/>
</a>
</div>
<!--<div id="slideNavigation"></div>-->
</div>
<!-- /#hero-nav -->
</div>
<!-- /#hero-cycle -->
</div>
<!-- /#hero -->
</div>
Maybe a bit complex to explain. I have a grid with 9 images 100 x 100 px like this (each number symbolize a picture):
1 2 3
4 5 6
7 8 9
What I want is that the user can drag and drop e.g. 9 over 1 and they change places like this:
9 2 3
4 5 6
7 8 1
Sortables from jquery UI will not work since their solution is using floats. That will "push" all the boxes to the right or left e.g.:
9 1 2
3 4 5
6 7 8
thanks in advance.
This uses both Draggable and Droppable. The Draggable reverts to it's original position on drop. When dragging starts, the Draggable creates a function to specify where to insert the Droppable that the item gets dropped on. When the item is dropped the drop function inserts the dragged item after the item it was dropped on and invokes the insert function on the dropped item to move the Droppable to the correct position.
$(function() {
$('.item').draggable( {
containment: 'parent',
revert: true,
revertDuration: 0,
start: function() {
var that = $(this);
var previous = that.prev( '.item:last' );
var next = that.next( '.item:first' );
that.data( 'insert' , function(elem) {
if (previous.size() > 0) {
$(elem).insertAfter(previous);
}
else if (next.size() > 0) {
$(elem).insertBefore(next);
}
});
}
});
$('.item').droppable( {
accept: '.item',
drop: function(event, ui) {
var elem = $(this);
if (elem.siblings('.item').size() > 1) {
ui.draggable.insertAfter(elem);
var insert = ui.draggable.data('insert');
insert(elem);
}
else { // case where there are only two elements, swap
var parent = elem.closest('.container');
var first = parent.children( '.item:first' );
var last = parent.children( '.item:last' );
last.insertBefore( first );
}
}
});
});
<div id="container">
<span class="item">1</span>
<span class="item">2</span>
<span class="item">3</span>
<span class="item">4</span>
<span class="item">5</span>
</div>
take a look at this plugin:
http://github.com/brandonaaron/jquery-swap/tree/master
Thanks for the fast replies!
Your solutions looks good but the first one throws some errors when changing position 1 and 2. The second one is not quite there. But they help alot!
I have tried to make some code that I think is a step in the right direction. What do you think?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
<title>Drag drop 1</title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.1.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".item").draggable({
// Elements cannot go outside #container
containment: 'parent',
// Make sure the element can only be dropped in a grid
grid: [150,150],
start: function(event, ui) {
// Make sure picture always are on top when dragged (z-index)
$(this).css({'z-index' : '100'});
// Show start dragged position
var Startpos = $(this).position();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
},
stop: function(event, ui) {
// Revert to default layer position when dropped (z-index)
$(this).css({'z-index' : '10'});
// Show dropped position
var Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
}
});
});
</script>
<style>
#container {
width:480px;
border:1px solid #000;
}
.item {
position:relative;
width:150px;
height:150px;
z-index:10;
}
</style>
</head>
<body>
<div id="container">
<img id="productid_1" src="images/pic1.jpg" class="item" alt="" title="" /><img id="productid_2" src="images/pic2.jpg" class="item" alt="" title="" /><img id="productid_3" src="images/pic3.jpg" class="item" alt="" title="" /><img id="productid_4" src="images/pic4.jpg" class="item" alt="" title="" /><img id="productid_5" src="images/pic5.jpg" class="item" alt="" title="" /><img id="productid_6" src="images/pic6.jpg" class="item" alt="" title="" /><img id="productid_7" src="images/pic7.jpg" class="item" alt="" title="" /><img id="productid_8" src="images/pic8.jpg" class="item" alt="" title="" /><img id="productid_9" src="images/pic9.jpg" class="item" alt="" title="" />
</div>
<div style="clear:both;"></div>
<div id="start">Waiting...</div>
<div id="stop">Waiting...</div>
</body>
</html>