JQuery Mobile End Drag (modular development, touch event, Webpack) _jquery

Source: Internet
Author: User
Tags bind

With jquery it is easy to pull the CP end. But it's not good to use on the mobile side. So I wrote a drag-and-drop demo on the mobile side, and the main event used was the touch event (Touchstart,touchmove and Touchend).

The function of this demo is that the element that can be dragged (here is the picture) is in the list, these elements can be dragged to the specified area, after the element is inserted into the console, the original drag element is returned to the original position, and the new element can still be dragged in the console and dragged out of the console.

In this demo one uses three modules, namely AJAX module, drag module, position module. Ajax modules are used to implement AJAX requests (so the image resources are obtained through AJAX requests), the drag module is used to implement element dragging and position modules are used to implement element position (such as location initialization, recovery, removal). The demo's entry file is Indx.js and the previous three module files are saved in the same folder. After the encoding is complete, it is packaged by Webpack. The development code is in the app folder, and the packaged code is in the build folder.

I. Introduction TO TOUCH Events

There are three touch events, namely Touchstart,touchmove and Touchend. The Touchstart event is triggered when the finger touches the screen. Touchmove is triggered continuously when the finger slides on the screen. When this event occurs, the default is canceled and the page scrolling can be organized. The touchend is triggered when the finger leaves from the screen. The event objects for these three touch events include the following three properties in addition to the common properties for mouse events:

Touches: An array of touchscreen objects that represent the touch operations of the current trace.

Targettouches: An array of touch objects that are specific to the event target.

Changetouches: An array of touch objects that indicate what has changed since the last time it was touched.

In this case, we need to get the position of the touch point relative to the viewport, and I'm using Event.targettouches[0].clientx and Event.targettouches[0].clienty.

Two. Code for AJAX modules

var $ = require (' jquery ');
var ajax = {
//Get an initial list of drag-and-drop pictures
getinitimg:function (parent) {
var num =;
$.ajax ({
type: "Get",
async:false,//uses synchronous loading here, because the picture must be loaded to do the other action
URL: '/home/picwall/index ',
Success:function (Result) {
if (result.status = = 1) {
$.each (result.data, function (index,item) {
var src = ITEM.PIC_SRC;
var width = parseint (item.width);
var height = parseint (item.height);
var ratio = Num/height;
var img = $ ('). attr ("src", src). Height (num). Width (parseint (width * ratio));
Parent.append (IMG);
});
}
,
dataType: ' JSON '
};
}
; Module.exports = ajax;//exposes Ajax modules

Three. code for the position module

var $ = require (' jquery '); var position = {//initialization location, gap is an object that represents the spacing of elements init:function (parent,gap) {var dragelem = Parent.children ();//Ensure that the parent element is relative positioning if (par
Ent.css (' position ')!== "relative") {parent.css (' position ', ' relative ');} parent.css ({' width ': ' 100% ', ' z-index ': ' 10 ')
});
Width of current list contents var listwidth = 0;
In the first few columns var j = 0; Dragelem.each (function (Index,elem) {var Curele = $ (elem);//Set the initial position of the element Curele.css ({position: "absolute", top:gap. Y, Left:listwidth + gap.
X});
Add a unique identifier for each element, which is useful when restoring the initial position curele.attr (' index ', index); Save the initial position of the element Position.coord.push ({x:listwidth + gap). X, Y:gap.
Y});
j + +; Sets the height of the parent element Parent.height (parseint (curele.css (' top ')) + curele.height () + gap.
Y);
ListWidth = Curele.offset (). Left + curele.width ();
}); Addto:function (Child,parent,target) {//the parent element's coordinate var Parentpos = {X:parent.offset () in the viewport) is inserted into the parent element. Left, Y:
Parent.offset (). Top};
The coordinates of the target position relative to the viewport var Targetpos = {X:target.offset (). Left, Y:target.offset (). Top}; Make sure the parent element is relative positioning if (parent.css (' position ')!== "relative"){parent.css ({' position ': ' relative '});}
Parent.css ({' Z-index ': ' 12 '});
Inserts a child element into the parent element parent.append. Determines the position of the child element in the parent element and guarantees the size of the child element unchanged Child.css ({position:absolute, top:targetpos.y-parentpos.y, left:targetpos.x-parent
Pos.x, Width:target.width (), Height:target.height ()}); Restore:function (Elem) {//Get element's identity var index = parseint (elem.attr (' index ')); Elem.css ({top:position.co Ord[index]. Y, Left:position.coord[index].
X}); },//Drag the initial coordinates of the element coord:[],//Determine if element A is within the range of element B israng:function (Control,draglistpar, $target) {var issituate = undefined; if ( Control.offset (). Top > Draglistpar.offset (). Top} {issituate = $target. Offset (). Top > Control.offset (). Top && Amp $target. Offset (). Left > Control.offset ()-left && ($target. Offset (). Left + $target. Width ()) < (
Control.offset (). Left + control.width ()); }else{issituate = ($target. Offset (). Top + $target. Height ()) < (Control.offset ()-top + control.height ()) && $ Target.Offset (). Top > CONTROL.OFfset (). Top && $target. Offset (). Left > Control.offset ()-left && ($target. Offset (). Left + $
Target.width ()) < (Control.offset (). Left + control.width ());
return issituate;
}
}; Module.exports = position;

four. Drag module code

var $ = require (' jquery ');
var position = require ('./position.js '); var drag = {//drag element's parent element ID dragparen:undefined,//console ID value control:undefined,//move block relative viewport position position:{x:undefined, Y:undef INED},//The position of the touch point relative to the viewport, the touchpos:{x:undefined, y:undefined}, and/or the position of the touch point relative to the viewport at the start of the touch starttouchpos:{x:undefined, Y : undefined},///Touch point relative to the position of the move block touchoffsetpos:{x:undefined, y:undefined},//Get the value of drag element parent element ID and console ID setid:function ( Draglist,control) {this.dragparent = draglist; This.control = control;}, Touchstart:function (e) {var target = E.target;
/block bubbling e.stoppropagation ();
Prevents the browser from default scaling and scrolling E.preventdefault ();
var $target = $ (target);
When the finger just touches the screen, the position of the touch point drag.starttouchpos.x = E.targettouches[0].clientx;
Drag.starttouchpos.y = E.targettouches[0].clienty;
The position of the touch element relative to the viewport is drag.position.x = $target. Offset (). Left;
DRAG.POSITION.Y = $target. Offset (). Top;
The position of the touch point relative to the viewport, constantly updating drag.touchpos.x = E.targettouches[0].clientx In the course of sliding;
Drag.touchpos.y = E.targettouches[0].clienty; The position of the touch point relative to the touch element Drag.touchoffsetpos.
X = drag.touchpos.x-drag.position.x;
Drag.touchoffsetpos.y = DRAG.TOUCHPOS.Y-DRAG.POSITION.Y;
Bind the target element to the Touchmove event $target. Unbind (' Touchmove '). On (' Touchmove ', drag.touchmove); }, Touchmove:function (e) {var target = E.target;//Block bubbling e.stoppropagation ();//block browser default zoom and scrolling E.preventdefault (); var $tar
Get = $ (target);
Get the position of the touch point drag.touchpos.x = E.targettouches[0].clientx;
Drag.touchpos.y = E.targettouches[0].clienty;
Modify the position of the move block $target. Offset ({top:drag.touchpos.y-drag.touchoffsetpos.y, left:drag.touchpos.x-drag.touchoffsetpos.x
});
Bind the move element to the Touchend event $target. Unbind (' Touchend '). On (' Touchend ', drag.touchend); }, Touchend:function (e) {var target = E.target;//Block bubbling e.stoppropagation ();//block browser default zoom and scrolling E.preventdefault (); var $targ
ET = $ (target);
var parent = $target. Parent ();
Gets the parent element of the console and drag element list var control = $ ("#" + Drag.control);
var Draglistpar = $ (' # ' + drag.dragparent);
Whether the drag element is located in the console var Sitcontrol = Position.israng (Control, Draglistpar, $target); Drag ends if dragging the element's parent element is a drag list if (PARENT.ATTR (' id ') = = = Drag.dragparent) {//If the element is in the console if (Sitcontrol) {var dragchild = $target. Clone ()//Bind the cloned element Touchstar
T event dragchild.unbind (' Touchstart '). On (' Touchstart ', drag.touchstart);
Insert the cloned elements into the console position.addto (Dragchild, control, $target);
//Restore the original touch element to the initial position position.restore ($target); 
If the parent element of the drag element is the console after the drag is finished, and the element is dragged out of the console if (parent.attr (' id ') = = Drag.control &&!sitcontrol) {$target. Remove ();}
}
}; Module.exports = drag;

Five. Entry file Index.js code

Require ('.. /css/base.css ');
Require ('.. /css/drag.css ');
var $ = require (' jquery ');
var drag = require ('./drag.js ');
var position = require ('./position.js ');
var ajax = require ('./ajax.js ');
var draglist = $ (' #dragList ');
Drag-and-drop element level, vertical spacing
var gap = {
x:20,
y:10
};
Get a list of drag-and-drop elements via Ajax
ajax.getinitimg (draglist);
Initializes the position of the drag element
Position.init (DRAGLIST,GAP);
Sets the height of the console. The height of the console is the height of the screen minus the cover of the drag list
var control = $ (' #control ');
Control.height ($ (window). Height ()-draglist.height ());
Bind Touchstart Event
var Dragelem = Draglist.children () to each drag element;
Dragelem.each (function (Index,elem) {
$ (elem). Unbind (' Touchstart '). On (' Touchstart ', Drag.touchstart);
});
The ID value of the parent element of the drag element is Draglist, and the ID value of the console is control
drag.setid (' draglist ', ' control ');

Six. Webpack Packing

Using the idea of modular programming, the implementation of different functions in different modules, what needs to be used to use require () to introduce, but the browser does not have the definition of require method. So the above code does not run directly in the browser, it needs to be packaged first. If you're not familiar with Webpack you can check out this article, Webpack's configuration file is as follows:

var autohtml = require (' Html-webpack-plugin ');
var webpack = require (' Webpack ');
var extracttextwebpack = require (' Extract-text-webpack-plugin ');//The plugin can detach the CSS file and place the CSS file in
a separate file Module.exports = {
entry:{
' index ': './app/js/index.js ',
' jquery ': [' jquery ']
},
output:{
Path: './build/',
filename: ' Js/[name].js '
},
module:{
loaders:[
{
test:/\.css/,
loader:extractTextWebpack.extract (' style ', ' CSS ')
}
]
},
plugins:[
New Extracttextwebpack (' Css/[name].css ', {
allchunks:true
}),
new Webpack.optimize.CommonsChunkPlugin ({
name: ' jquery ',
filename: ' Js/jquery.js '
}],
new autohtml ({
title: "Drag",
filename : "drag.html",
Template: './app/darg.html ',
inject:true
}
]
};

The above is a small series for you to introduce the jquery mobile end drag (modular development, touch events, Webpack), hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.