Jquery Drag and Drop with sortable Unexpexted behaviour - javascript

I am trying to make a drag and drop with sortable . I have Two panel left and right .In left panel I have some drag element which can be clone or without clone.
I have to drop left panel element in right panel .In this case we can sort trash element. In my case Drag drop and sortable working fine but some time it shows different behavior please refer attached images. Live Demo
<script type="text/javascript">
var new_id = 20;
$(document).ready(function () {
var $gallery = $(".gallery");
$("li", $gallery).draggable({
cursor: 'move',
revert: 'invalid',
containment: "#area",
helper: function () {
//alert($(this).attr('class'));
var cloned = $(this).clone();
cloned.attr('id', (++new_id).toString());
return cloned;
},
distance: 20
});
$("#trash").droppable({
tolerance: 'pointer',
items: "li:not(.editable)",
accept: function (event, ui) {
return true;
},
drop: function (event, ui) {
var id = ui.draggable[0].id;
var color = $(ui.draggable).css("background-color");
var obj;
if ($(ui.helper).hasClass('draggable')) {
obj = SetDropElementStyle($(ui.helper).clone(), color);
$(this).append(obj);
}
}
}).sortable({
revert: false,
items: "li:not(.editable)",
containment: "#trash",
opacity: 0.6
});
});
function SetDropElementStyle(_obj, _color) {
var imgtype = "";
var itemWidth = 50;
if ((_color == "rgb(70, 130, 180)") || (_color == "#4682B4")) {
$(_obj).find('img').remove();
var TypeID = $(_obj).attr('typeid');
imgtype = "R";
_obj.removeClass('draggable ui-draggable ui-draggable-dragging recipintlist').addClass('flowIn').removeAttr('style');
if ($.trim(_obj[0].innerText).length > 0) {
itemWidth = ($.trim(_obj[0].innerText).length + 1) * 10;
}
$(_obj).css({ 'width': itemWidth });
$("[typeid|='" + TypeID + "']").remove();
}
if ((_color == "rgb(237, 125, 49)") || (_color == "#ED7D31")) {
var delayText = "+<span>0</span>h <span>01</span>mn"
_obj.removeClass('draggable ui-draggable ui-draggable-dragging actionlistDelay').addClass('delay').removeAttr('style');
imgtype = "D";
_obj.append(delayText);
}
if ((_color == "rgb(186, 56, 56)") || (_color == "#ba3838")) {
$(_obj).find('span').remove();
var haltText = "<div style='width:1px;color:white;'>H<br/>A<br/>L<br/>T</div>";
_obj.removeClass('draggable ui-draggable ui-draggable-dragging actionlistHalt').addClass('halt').removeAttr('style');
imgtype = "H";
_obj.append(haltText);
}
return _obj;
}
</script>

Related

Adding translate class to mobile navigation

I am new to javascript and I don't quite know where I should be adding in my class that allows for the website to be translated.
I have a mobile nav that appears when the screen width is X small and in that nav I have numerous directional buttons that lead to other parts of the website, BUT two buttons (The english and Chinese translation buttons) don't work when being pressed.
I assume this is because I have not added the 'lang' class in my 'is-mobile' class but I am unaware of how to do this.
Here is my code
(function($) {
var $window = $(window),
$body = $('body'),
$header = $('#header'),
$banner = $('#banner'),
settings = {
banner: {
// Indicators (= the clickable dots at the bottom).
indicators: true,
// Transition speed (in ms)
// For timing purposes only. It *must* match the transition speed of "#banner > article".
speed: 1500,
// Transition delay (in ms)
delay: 5000,
// Parallax intensity (between 0 and 1; higher = more intense, lower = less intense; 0 = off)
parallax: 0.25
}
};
/**
* Applies parallax scrolling to an element's background image.
* #return {jQuery} jQuery object.
*/
$.fn._parallax = (browser.name == 'ie' || browser.name == 'edge' || browser.mobile) ? function() {
return $(this)
} : function(intensity) {
var $window = $(window),
$this = $(this);
if (this.length == 0 || intensity === 0)
return $this;
if (this.length > 1) {
for (var i = 0; i < this.length; i++)
$(this[i])._parallax(intensity);
return $this;
}
if (!intensity)
intensity = 0.25;
$this.each(function() {
var $t = $(this),
on, off;
on = function() {
$t.css('background-position', 'center 100%, center 100%, center 0px');
$window
.on('scroll._parallax', function() {
var pos = parseInt($window.scrollTop()) - parseInt($t.position().top);
$t.css('background-position', 'center ' + (pos * (-1 * intensity)) + 'px');
});
};
off = function() {
$t
.css('background-position', '');
$window
.off('scroll._parallax');
};
breakpoints.on('<=medium', off);
breakpoints.on('>medium', on);
});
$window
.off('load._parallax resize._parallax')
.on('load._parallax resize._parallax', function() {
$window.trigger('scroll');
});
return $(this);
};
/**
* #return {jQuery} jQuery object.
*/
$.fn._slider = function(options) {
var $window = $(window),
$this = $(this);
if (this.length == 0)
return $this;
if (this.length > 1) {
for (var i = 0; i < this.length; i++)
$(this[i])._slider(options);
return $this;
}
// Vars.
var current = 0,
pos = 0,
lastPos = 0,
slides = [],
indicators = [],
$indicators,
$slides = $this.children('article'),
intervalId,
isLocked = false,
i = 0;
// Turn off indicators if we only have one slide.
if ($slides.length == 1)
options.indicators = false;
// Functions.
$this._switchTo = function(x, stop) {
if (isLocked || pos == x)
return;
isLocked = true;
if (stop)
window.clearInterval(intervalId);
// Update positions.
lastPos = pos;
pos = x;
// Hide last slide.
slides[lastPos].removeClass('top');
if (options.indicators)
indicators[lastPos].removeClass('visible');
// Show new slide.
slides[pos].addClass('visible').addClass('top');
if (options.indicators)
indicators[pos].addClass('visible');
// Finish hiding last slide after a short delay.
window.setTimeout(function() {
slides[lastPos].addClass('instant').removeClass('visible');
window.setTimeout(function() {
slides[lastPos].removeClass('instant');
isLocked = false;
}, 100);
}, options.speed);
};
// Indicators.
if (options.indicators)
$indicators = $('<ul class="indicators"></ul>').appendTo($this);
// Slides.
$slides
.each(function() {
var $slide = $(this),
$img = $slide.find('img');
// Slide.
$slide
.css('background-image', 'url("' + $img.attr('src') + '")')
.css('background-position', ($slide.data('position') ? $slide.data('position') : 'center'));
// Add to slides.
slides.push($slide);
// Indicators.
if (options.indicators) {
var $indicator_li = $('<li>' + i + '</li>').appendTo($indicators);
// Indicator.
$indicator_li
.data('index', i)
.on('click', function() {
$this._switchTo($(this).data('index'), true);
});
// Add to indicators.
indicators.push($indicator_li);
}
i++;
})
._parallax(options.parallax);
// Initial slide.
slides[pos].addClass('visible').addClass('top');
if (options.indicators)
indicators[pos].addClass('visible');
// Bail if we only have a single slide.
if (slides.length == 1)
return;
// Main loop.
intervalId = window.setInterval(function() {
current++;
if (current >= slides.length)
current = 0;
$this._switchTo(current);
}, options.delay);
};
// Breakpoints.
breakpoints({
xlarge: ['1281px', '1680px'],
large: ['981px', '1280px'],
medium: ['737px', '980px'],
small: ['481px', '736px'],
xsmall: [null, '480px']
});
// Play initial animations on page load.
$window.on('load', function() {
window.setTimeout(function() {
$body.removeClass('is-preload');
}, 100);
});
// Mobile?
if (browser.mobile)
$body.addClass('is-mobile', 'tr');
else {
breakpoints.on('>medium', function() {
$body.removeClass('is-mobile');
});
breakpoints.on('<=medium', function() {
$body.addClass('is-mobile');
});
}
// Dropdowns.
$('#nav > ul').dropotron({
alignment: 'center',
hideDelay: 400
});
// Header.
if ($banner.length > 0 &&
$header.hasClass('alt')) {
$window.on('resize', function() {
$window.trigger('scroll');
});
$banner.scrollex({
bottom: $header.outerHeight(),
terminate: function() {
$header.removeClass('alt');
},
enter: function() {
$header.addClass('alt');
},
leave: function() {
$header.removeClass('alt');
$header.addClass('reveal');
}
});
}
// Banner.
$banner._slider(settings.banner);
// Off-Canvas Navigation.
// Navigation Panel Toggle.
$('')
.appendTo($header);
// Navigation Panel.
$(
'<div id="navPanel">' +
'<nav>' +
$('#nav').navList() +
'</nav>' +
'' +
'</div>'
)
.appendTo($body)
.panel({
delay: 500,
hideOnClick: true,
hideOnSwipe: true,
resetScroll: true,
resetForms: true,
side: 'right'
});
// onclick behavior
$('.lang').click('touchstart', function() {
var lang = $(this).attr('id'); // obtain language id
// translate all translatable elements
$('.tr').each(function(i) {
$(this).text(aLangKeys[lang][$(this).attr('key')]);
});
});
document.getElementById('ch').onclick = function() {
var lang = $(this).attr('id'); // obtain language id
// translate all translatable elements
$('.tr').each(function(i) {
$(this).text(aLangKeys[lang][$(this).attr('key')]);
});
}
// preparing language file
var aLangKeys = new Array();
aLangKeys['en'] = new Array();
aLangKeys['ch'] = new Array();
aLangKeys['en']['home'] = 'Home';
aLangKeys['en']['about'] = 'About Us';
aLangKeys['en']['serv'] = 'Services';
aLangKeys['en']['sem'] = 'Search Engine Marketing';
aLangKeys['en']['webdev'] = 'Website Development';
aLangKeys['en']['app'] = 'Mobile App Development';
aLangKeys['en']['tbd'] = 'Technical Business Development';
aLangKeys['en']['ourteam'] = 'Our Team';
aLangKeys['en']['contactus'] = 'Contact Us';
aLangKeys['en']['submit'] = 'Send Message';
aLangKeys['en']['reset'] = 'Reset';
aLangKeys['ch']['home'] = '首页';
aLangKeys['ch']['about'] = '关于我们';
aLangKeys['ch']['serv'] = '服务';
aLangKeys['ch']['sem'] = '谷歌与雅虎推广';
aLangKeys['ch']['webdev'] = '品牌网站建设';
aLangKeys['ch']['app'] = 'APP 开发';
aLangKeys['ch']['tbd'] = '加拿大工商业与市场拓展';
aLangKeys['ch']['ourteam'] = '我们的团队';
aLangKeys['ch']['contactus'] = '联络我们';
aLangKeys['ch']['submit'] = '发留言';
aLangKeys['ch']['reset'] = '重新';
})(jQuery);
<!-- Header -->
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<header id="header" class="alt">
<h1>
<img src="images/Artboard%201.png" alt="logo" class="logo">
</h1>
<nav id="nav">
<ul class="translate">
<li>Home</li>
<li>About Us</li>
<li>
Services
<ul>
<li>Search Engine Marketing</li>
<li>Website Development </li>
<li>App Development</li>
<li>Technical Business Development</li>
</ul>
</li>
<li>Our Team</li>
<li>English</li>
<li>中文</li>
<li>Contact Us</li>
</ul>
</nav>
</header>
<!-- begin snippet: js hide: false console: true babel: false -->
Here is the other part of JS code:
(function($) {
/**
* Generate an indented list of links from a nav. Meant for use with panel().
* #return {jQuery} jQuery object.
*/
$.fn.navList = function() {
var $this = $(this);
$a = $this.find('a'),
b = [];
$a.each(function() {
var $this = $(this),
indent = Math.max(0, $this.parents('li').length - 1),
href = $this.attr('href'),
target = $this.attr('target');
b.push(
'<a ' +
'class="link depth-' + indent + '"' +
((typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
((typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
'>' +
'<span class="indent-' + indent + '"></span>' +
$this.text() +
'</a>'
);
});
return b.join('');
};
/**
* Panel-ify an element.
* #param {object} userConfig User config.
* #return {jQuery} jQuery object.
*/
$.fn.panel = function(userConfig) {
// No elements?
if (this.length == 0)
return $this;
// Multiple elements?
if (this.length > 1) {
for (var i = 0; i < this.length; i++)
$(this[i]).panel(userConfig);
return $this;
}
// Vars.
var $this = $(this),
$body = $('body'),
$window = $(window),
id = $this.attr('id'),
config;
// Config.
config = $.extend({
// Delay.
delay: 0,
// Hide panel on link click.
hideOnClick: false,
// Hide panel on escape keypress.
hideOnEscape: false,
// Hide panel on swipe.
hideOnSwipe: false,
// Reset scroll position on hide.
resetScroll: false,
// Reset forms on hide.
resetForms: false,
// Side of viewport the panel will appear.
side: null,
// Target element for "class".
target: $this,
// Class to toggle.
visibleClass: 'visible'
}, userConfig);
// Expand "target" if it's not a jQuery object already.
if (typeof config.target != 'jQuery')
config.target = $(config.target);
// Panel.
// Methods.
$this._hide = function(event) {
// Already hidden? Bail.
if (!config.target.hasClass(config.visibleClass))
return;
// If an event was provided, cancel it.
if (event) {
event.preventDefault();
event.stopPropagation();
}
// Hide.
config.target.removeClass(config.visibleClass);
// Post-hide stuff.
window.setTimeout(function() {
// Reset scroll position.
if (config.resetScroll)
$this.scrollTop(0);
// Reset forms.
if (config.resetForms)
$this.find('form').each(function() {
this.reset();
});
}, config.delay);
};
// Vendor fixes.
$this
.css('-ms-overflow-style', '-ms-autohiding-scrollbar')
.css('-webkit-overflow-scrolling', 'touch');
// Hide on click.
if (config.hideOnClick) {
$this.find('a')
.css('-webkit-tap-highlight-color', 'rgba(0,0,0,0)');
$this
.on('click', 'a', function(event) {
var $a = $(this),
href = $a.attr('href'),
target = $a.attr('target');
if (!href || href == '#' || href == '' || href == '#' + id)
return;
// Cancel original event.
event.preventDefault();
event.stopPropagation();
// Hide panel.
$this._hide();
// Redirect to href.
window.setTimeout(function() {
if (target == '_blank')
window.open(href);
else
window.location.href = href;
}, config.delay + 10);
});
}
// Event: Touch stuff.
$this.on('touchstart', function(event) {
$this.touchPosX = event.originalEvent.touches[0].pageX;
$this.touchPosY = event.originalEvent.touches[0].pageY;
})
$this.on('touchmove', function(event) {
if ($this.touchPosX === null ||
$this.touchPosY === null)
return;
var diffX = $this.touchPosX - event.originalEvent.touches[0].pageX,
diffY = $this.touchPosY - event.originalEvent.touches[0].pageY,
th = $this.outerHeight(),
ts = ($this.get(0).scrollHeight - $this.scrollTop());
// Hide on swipe?
if (config.hideOnSwipe) {
var result = false,
boundary = 20,
delta = 50;
switch (config.side) {
case 'left':
result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX > delta);
break;
case 'right':
result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX < (-1 * delta));
break;
case 'top':
result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY > delta);
break;
case 'bottom':
result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY < (-1 * delta));
break;
default:
break;
}
if (result) {
$this.touchPosX = null;
$this.touchPosY = null;
$this._hide();
return false;
}
}
// Prevent vertical scrolling past the top or bottom.
if (($this.scrollTop() < 0 && diffY < 0) ||
(ts > (th - 2) && ts < (th + 2) && diffY > 0)) {
event.preventDefault();
event.stopPropagation();
}
});
// Event: Prevent certain events inside the panel from bubbling.
$this.on('click touchend touchstart touchmove', function(event) {
event.stopPropagation();
});
// Event: Hide panel if a child anchor tag pointing to its ID is clicked.
$this.on('click', 'a[href="#' + id + '"]', function(event) {
event.preventDefault();
event.stopPropagation();
config.target.removeClass(config.visibleClass);
});
// Body.
// Event: Hide panel on body click/tap.
$body.on('click touchend', function(event) {
$this._hide(event);
});
// Event: Toggle.
$body.on('click', 'a[href="#' + id + '"]', function(event) {
event.preventDefault();
event.stopPropagation();
config.target.toggleClass(config.visibleClass);
});
// Window.
// Event: Hide on ESC.
if (config.hideOnEscape)
$window.on('keydown', function(event) {
if (event.keyCode == 27)
$this._hide(event);
});
return $this;
};
/**
* Apply "placeholder" attribute polyfill to one or more forms.
* #return {jQuery} jQuery object.
*/
$.fn.placeholder = function() {
// Browser natively supports placeholders? Bail.
if (typeof(document.createElement('input')).placeholder != 'undefined')
return $(this);
// No elements?
if (this.length == 0)
return $this;
// Multiple elements?
if (this.length > 1) {
for (var i = 0; i < this.length; i++)
$(this[i]).placeholder();
return $this;
}
// Vars.
var $this = $(this);
// Text, TextArea.
$this.find('input[type=text],textarea')
.each(function() {
var i = $(this);
if (i.val() == '' ||
i.val() == i.attr('placeholder'))
i
.addClass('polyfill-placeholder')
.val(i.attr('placeholder'));
})
.on('blur', function() {
var i = $(this);
if (i.attr('name').match(/-polyfill-field$/))
return;
if (i.val() == '')
i
.addClass('polyfill-placeholder')
.val(i.attr('placeholder'));
})
.on('focus', function() {
var i = $(this);
if (i.attr('name').match(/-polyfill-field$/))
return;
if (i.val() == i.attr('placeholder'))
i
.removeClass('polyfill-placeholder')
.val('');
});
// Password.
$this.find('input[type=password]')
.each(function() {
var i = $(this);
var x = $(
$('<div>')
.append(i.clone())
.remove()
.html()
.replace(/type="password"/i, 'type="text"')
.replace(/type=password/i, 'type=text')
);
if (i.attr('id') != '')
x.attr('id', i.attr('id') + '-polyfill-field');
if (i.attr('name') != '')
x.attr('name', i.attr('name') + '-polyfill-field');
x.addClass('polyfill-placeholder')
.val(x.attr('placeholder')).insertAfter(i);
if (i.val() == '')
i.hide();
else
x.hide();
i
.on('blur', function(event) {
event.preventDefault();
var x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');
if (i.val() == '') {
i.hide();
x.show();
}
});
x
.on('focus', function(event) {
event.preventDefault();
var i = x.parent().find('input[name=' + x.attr('name').replace('-polyfill-field', '') + ']');
x.hide();
i
.show()
.focus();
})
.on('keypress', function(event) {
event.preventDefault();
x.val('');
});
});
// Events.
$this
.on('submit', function() {
$this.find('input[type=text],input[type=password],textarea')
.each(function(event) {
var i = $(this);
if (i.attr('name').match(/-polyfill-field$/))
i.attr('name', '');
if (i.val() == i.attr('placeholder')) {
i.removeClass('polyfill-placeholder');
i.val('');
}
});
})
.on('reset', function(event) {
event.preventDefault();
$this.find('select')
.val($('option:first').val());
$this.find('input,textarea')
.each(function() {
var i = $(this),
x;
i.removeClass('polyfill-placeholder');
switch (this.type) {
case 'submit':
case 'reset':
break;
case 'password':
i.val(i.attr('defaultValue'));
x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');
if (i.val() == '') {
i.hide();
x.show();
} else {
i.show();
x.hide();
}
break;
case 'checkbox':
case 'radio':
i.attr('checked', i.attr('defaultValue'));
break;
case 'text':
case 'textarea':
i.val(i.attr('defaultValue'));
if (i.val() == '') {
i.addClass('polyfill-placeholder');
i.val(i.attr('placeholder'));
}
break;
default:
i.val(i.attr('defaultValue'));
break;
}
});
});
return $this;
};
/**
* Moves elements to/from the first positions of their respective parents.
* #param {jQuery} $elements Elements (or selector) to move.
* #param {bool} condition If true, moves elements to the top. Otherwise, moves elements back to their original locations.
*/
$.prioritize = function($elements, condition) {
var key = '__prioritize';
// Expand $elements if it's not already a jQuery object.
if (typeof $elements != 'jQuery')
$elements = $($elements);
// Step through elements.
$elements.each(function() {
var $e = $(this),
$p,
$parent = $e.parent();
// No parent? Bail.
if ($parent.length == 0)
return;
// Not moved? Move it.
if (!$e.data(key)) {
// Condition is false? Bail.
if (!condition)
return;
// Get placeholder (which will serve as our point of reference for when this element needs to move back).
$p = $e.prev();
// Couldn't find anything? Means this element's already at the top, so bail.
if ($p.length == 0)
return;
// Move element to top of parent.
$e.prependTo($parent);
// Mark element as moved.
$e.data(key, $p);
}
// Moved already?
else {
// Condition is true? Bail.
if (condition)
return;
$p = $e.data(key);
// Move element back to its original location (using our placeholder).
$e.insertAfter($p);
// Unmark element as moved.
$e.removeData(key);
}
});
};
})(jQuery);
Here is the code snippet of my dropotron jquery file I have been using for the menu drop down if needed.
Where would I go to insert my lang class so that when it is in mobile nav the class is recognized? Thank you!
I figured it out!
I needed to add the class 'tr' into:
'class="tr link depth-' + indent + '"' +
Just forgot that little thing...

jQuery UI : How can I know that the div are center on drag event

If I have two or more divs or p tags. I want to know how can I get the center with each elements means in my fiddle example ( that I will provide below ) if I drag the the "I am title H3" ( that is my H3 tag ) to the "I am a Title H1" ( which is my H1 tag ) or to the "I am a parargraph p" ( which is my p tag ) a line that comes that indicate the two elements are center to each other.
var element = $(".draggable_element");
element.each(function() {
$(this).draggable({
zIndex: 999,
scroll: false,
refreshPosition: true,
});
});
Here is my fiddle.
The below code will help you to find the center of each element on dragging. https://jsfiddle.net/44ve3syv/4/
var element = $(".draggable_element");
element.each(function() {
$(this).draggable({
zIndex: 999,
scroll: false,
refreshPosition: true,
drag: function() {
console.log(1);
},
stop:function(){
checkIfCenter($(this));
}
});
});
checkIfCenter = function(el){
var cPos;
var elCenter = findCentre(el);
var isCenter = true;
$( ".draggable_element" ).each(function() {
cPos = findCentre($(this));
console.log(cPos);
if(cPos.x == elCenter.x && cPos.y == elCenter.y && isCenter){
isCenter = true;
}else{
isCenter = false;
}
});
if(isCenter){
alert("All elements came in center");
}
}
findCentre = function(el){
var offset = el.offset();
var width = el.width();
var height = el.height();
var pos = { x : parseInt(offset.left + width / 2),y : parseInt(offset.top + height / 2)}
return pos;
}

jQuery click mobile problems (slider)

I have coded a small script for scrolling in a vertical gallery on mobile devices – in browser everything works fine, but I can't make it work on my smartphone. What am I doing wrong?
Thats my query:
jQuery( '.single-cinema-cat .next' ).on('click touchstart', function () {
alert("The btn was clicked.");
if( jQuery( this ).hasClass( 'disabled' ) )
return;
jQuery( this ).addClass( 'disabled' );
var $el = jQuery( this );
if( jQuery( window ).innerWidth() >= 970 )
scrollVertical_next( $el );
else
scrollHorizontal_next( $el );
});
the click element is a span-element in my html markup – could this be a problem? screenshot of my markup: https://picload.org/image/ralwaarg/jquerymobile.png
please save me for further headaches :-)
scrollVertical_next
function scrollVertical_next($el) {
var $wrapper = $el.closest('.single-cinema-cat').find('.inner');
var margin = parseInt($wrapper.find('article').css('margin-bottom')) + parseInt($wrapper.find('article').css('margin-top'));
var current_height = parseInt($wrapper.find('ul').css('top'));
var single_height = $wrapper.find('article').outerHeight() + margin;
var target_height = current_height - single_height;
var total_height = $wrapper.find('ul').innerHeight();
var stopper_height = -1 * total_height + 4 * single_height;
if (target_height < stopper_height)
return;
$wrapper.find('ul').animate({
'top': target_height + 'px'
}, 250, 'swing', function() {
if (target_height > stopper_height)
$el.removeClass('disabled');
$el.closest('.single-cinema-cat').find('.prev').removeClass('disabled');
});
}
scrollHorizontal_next
function scrollHorizontal_next($el) {
var $wrapper = $el.closest('.single-cinema-cat').find('.inner');
var margin = parseInt($wrapper.find('article').css('margin-bottom')) + parseInt($wrapper.find('article').css('margin-top'));
var current_height = parseInt($wrapper.find('ul').css('top'));
var single_height = $wrapper.find('article').outerHeight() + margin;
var target_height = current_height - single_height;
var total_height = $wrapper.find('ul').innerHeight();
var stopper_height = -1 * total_height + 1 * single_height;
if (target_height < stopper_height)
return;
$wrapper.find('ul').animate({
'top': target_height + 'px'
}, 250, 'swing', function() {
if (target_height > stopper_height)
$el.removeClass('disabled');
$el.closest('.single-cinema-cat').find('.prev').removeClass('disabled');
});
}
Touch event must be handled this way
jQuery('.single-cinema-cat .next').on('click touchstart', function (event) {
event.stopPropagation();
event.preventDefault();
if (event.handled !== true) {
////////// your stuff //////////////////////////
alert("The btn was clicked.");
if (jQuery(this).hasClass('disabled'))
return;
jQuery(this).addClass('disabled');
var $el = jQuery(this);
if (jQuery(window).innerWidth() >= 970)
scrollVertical_next($el);
else
scrollHorizontal_next($el);
////////////////////////////////////////////////////
event.handled = true;
} else {
return false;
}
});

jQuery UI Droppable with an item dropped by default (without changing the markup structure)

I'm using .draggable() and .droppable() to calculate the price of the items that were dropped in the container, based on the weight and a constant defining the per gram price of all items.
Now I'd like to have one of the items dropped within the container by default, together with the correct calculations and the possibility to drag more/less items over the container. The positioning should be like image 1 when the reset button is pressed and I must be able to drag the default item out of the container just like the other draggables.
This is what it looks like now:
And this is how I want it to look like on page load:
I haven't found any documentation covering default droppables like this, so I don't really know where to start. I've prepared a Jsfiddle here: http://jsfiddle.net/gPFMk/ and a Jsbin for those who like it better http://jsbin.com/oxuguc/1/edit
var price = 0, math = '', items = [], state = 'outside', wprice = 209;
function calcPrice(math) {
price = 0;
weight = 0;
$('.counter-number').remove();
addticker(0);
console.log("Item array: " + items);
$.each( items, function( key, value ) {
price+= parseInt($(".draggable[data-item='" + value + "']").attr('id'));
weight+= $(".draggable[data-item='" + value + "']").data('weight');
loadticker(price);
});
$('#weight').html('<span>weight </span>' + weight + ' g');
}
function revertDraggable($selector) {
$selector.each(function() {
var $this = $(this),
position = $this.data("originalPosition");
if (position) {
$this.animate({
left: position.left,
top: position.top
}, 500, function() {
$this.data("originalPosition", null);
});
}
items = [];
$('#droppable').removeClass('active');
$('.counter-number').remove();
calcPrice();
});
}
$(function() {
$.each($('.draggable'), function() {
var $this = $(this),
weight = $this.data('weight');
$this.attr('id', weight*wprice);
});
$(".draggable").draggable({
revert: function (event, ui) {
$(this).data("draggable").originalPosition = {
top: 0,
left: 0
};
return !event;
},
cursor: "move",
cursorAt: {
top: 56,
left: 56
},
stack: "div",
containment: "#container",
scroll: false
});
$("#droppable").droppable({
drop: function(e, u) {
$(this).addClass('active');
if ($.inArray(u.draggable.data('item'), items) == -1) {
items.push(u.draggable.data('item'));
price = 0;
weight = 0;
calcPrice('add');
u.draggable.data('state', 'inside');
}
if (!u.draggable.data("originalPosition")) {
u.draggable.data("originalPosition",
u.draggable.data("draggable").originalPosition);
}
},
over: function() {
$(this).addClass('active');
},
out: function(e, u) {
if(u.draggable.data('state') == 'inside') {
u.draggable.data('state', 'outside');
var itemIndex = $.inArray(u.draggable.data('item'), items);
items.splice(itemIndex, 1);
price = $("#droppable").text();
calcPrice('remove');
}
if (items.length === 0)
$('#droppable').removeClass('active');
}
});
$('#container').on('click', '#reset', function() {
revertDraggable($(".draggable"));
});
});
<div id="container">
<div id="heft">
<div id="info">
<div id="price">
<span>price</span>
<div class="counter-wrap">
<div class="counter-number">
</div>
</div>€
</div>
<div id="weight">
<span>weight</span>
0 g
</div>
<button id="reset">Reset</button>
</div>
<div id="droppable"></div>
</div>
<div id="items">
<div class="draggable" data-item="3" data-weight="15" data-state="outside"><img src="http://wemakeawesomesh.it/nyancat/nyan.gif" width="90" height="90"></div>
<div class="draggable" data-item="2" data-weight="35" data-state="outside"><img src="http://wemakeawesomesh.it/nyancat/nyan.gif" width="90" height="90"></div>
<div class="draggable" data-item="1" data-weight="8" data-state="outside"><img src="http://wemakeawesomesh.it/nyancat/nyan.gif" width="90" height="90"></div>
</div>
</div>
If I move the code of one item to the droppable div like suggested, revertDraggable() and revert: won't work as expected.
Here's a solution that simulates an item drop for the first item on document load.
The difficulty was to mimic what happens during a drop:
$(".draggable[data-item='1']").attr(
"style",
"position: relative; z-index: 10; left: 300px; top: 30px"
);
var onDrop = function(e,u) {
if ($.inArray(u.draggable.data('item'), items) == -1) {
items.push(u.draggable.data('item'));
price = 0;
weight = 0;
calcPrice('add');
u.draggable.data('state', 'inside');
}
if (!u.draggable.data("originalPosition")) {
u.draggable.data("originalPosition",
u.draggable.data("draggable").originalPosition);
}
};
onDrop.call($("#droppable"),
{},{ draggable: $(".draggable[data-item='1']") }
);
Here is the link to the jsfiddle.

jQuery draggable applying multiple clicks after drag

I'm half way through updating my website and I've ran into an issue I can't seem to figure out. If you click the green button labeled "Alchemy Lab" an Alchemy Lab will pop up. After that if you drag the Lab once and click the red and green arrows in the Lab the counter works like it should with a max of 10. If you drag the Lab around 2 more times and then click the green or red arrow the count is off by 3. So every time you drop the Lab it adds another click on click. Any ideas on why or how to fix it? Thanks in advanced.
javascript:
function handleNewClicks() {
$(".pro_cell_3").click(function () {
var currentUp = parseInt($(this).parent().find('.pro_cell_2').text(), 10);
var maxUp = 10;
if (currentUp == maxUp) {
$(this).parent().find('.pro_cell_2').text("1");
} else {
$(this).parent().find('.pro_cell_2').text(currentUp + 1);
}
});
$(".pro_cell_4").click(function () {
var currentUp = parseInt($(this).parent().find('.pro_cell_2').text(), 10);
var maxUp = 10;
if ((currentUp - 1) == 0) {
$(this).parent().find('.pro_cell_2').text(maxUp);
} else {
$(this).parent().find('.pro_cell_2').text(currentUp - 1);
}
});
$(".up_cell_3").click(function () {
var currentUp = parseInt($(this).parent().find('.up_cell_2').text(), 10);
var maxUp = parseInt($(this).parent().find('.up_cell_2').attr("max"), 10);
var className = $(this).parent().parent().attr("class");
className = className.replace("ui-draggable ", "");
if (currentUp == maxUp) {
$(this).parent().find('.up_cell_2').text("1");
$(this).parent().parent().css({ 'background-image': 'url(images/' + className + '_1.png)' });
} else {
$(this).parent().find('.up_cell_2').text(currentUp + 1);
$(this).parent().parent().css({ 'background-image': 'url(images/' + className + '_' + (currentUp + 1) + '.png)' });
}
});
$(".up_cell_4").click(function () {
var currentUp = parseInt($(this).parent().find('.up_cell_2').text(), 10);
var maxUp = parseInt($(this).parent().find('.up_cell_2').attr("max"), 10);
var className = $(this).parent().parent().attr("class");
className = className.replace("ui-draggable ", "");
if ((currentUp - 1) == 0) {
$(this).parent().find('.up_cell_2').text(maxUp);
$(this).parent().parent().css({ 'background-image': 'url(images/' + className + '_' + maxUp + '.png)' });
} else {
$(this).parent().find('.up_cell_2').text(currentUp - 1);
$(this).parent().parent().css({ 'background-image': 'url(images/' + className + '_' + (currentUp - 1) + '.png)' });
}
});
}
function proCoding() {
proWrap = document.createElement('div');
$(proWrap).attr('class', 'pro_wrap');
proCell1 = document.createElement('span');
$(proCell1).attr('class', 'pro_cell_1');
proCell2 = document.createElement('span');
$(proCell2).attr('class', 'pro_cell_2');
proCell3 = document.createElement('span');
$(proCell3).attr('class', 'pro_cell_3');
proCell4 = document.createElement('span');
$(proCell4).attr('class', 'pro_cell_4');
proCell2.innerText = "1";
proWrap.appendChild(proCell1);
proWrap.appendChild(proCell2);
proWrap.appendChild(proCell3);
proWrap.appendChild(proCell4);
}
function upCoding() {
pos_top = $(window).scrollTop() + top_off_set;
pos_left = $(window).scrollLeft() + left_off_set;
upWrap = document.createElement('div');
$(upWrap).attr('class', 'up_wrap');
upCell1 = document.createElement('span');
$(upCell1).attr('class', 'up_cell_1');
upCell2 = document.createElement('span');
$(upCell2).attr('class', 'up_cell_2');
$(upCell2).attr('max', '10');
upCell3 = document.createElement('span');
$(upCell3).attr('class', 'up_cell_3');
upCell4 = document.createElement('span');
$(upCell4).attr('class', 'up_cell_4');
upCell2.innerText = "1";
upWrap.appendChild(upCell1);
upWrap.appendChild(upCell2);
upWrap.appendChild(upCell3);
upWrap.appendChild(upCell4);
newLab = document.createElement('div');
}
$(".nav_alchemy_lab").click(function () {
proCoding();
upCoding();
newLab.appendChild(proWrap);
newLab.appendChild(upWrap);
$(newLab).attr('class', 'ui-draggable alchemy_lab').appendTo('#cardPile').css({ 'top': pos_top, 'left': pos_left, 'background-image': 'url(images/alchemy_lab_1.png)' }).draggable({
containment: '#content', snap: true, stack: '#cardPile div', cursor: 'move',
start: function (e) {
},
stop: function (e) {
setTimeout(function () {
handleNewClicks()
}, 1);
}
})
});
$(".ui-draggable").draggable({
containment: '#content',
stack: '#cardPile div',
cursor: 'move'
});
$(".ui-droppable").droppable({
accept: '#cardPile div',
drop: handleCardDrop
});
function handleCardDrop(event, ui) {
$(ui.draggable).css('top', $(this).position().top);
var divWidth = ui.draggable.width();
var divLeft = $(this).position().left;
if (divWidth == 100) {
divLeft -= 0;
} else if (divWidth == 200) {
divLeft -= 100;
} else if (divWidth == 300) {
divLeft -= 100;
} else {
divLeft -= 0;
}
$(ui.draggable).css('left', divLeft);
}
Every time you finish dragging something, you run the function handleNewClicks().
$(newLab).attr('class', 'ui-draggable alchemy_lab').appendTo('#cardPile').css({ 'top': pos_top, 'left': pos_left, 'background-image': 'url(images/alchemy_lab_1.png)' }).draggable({
containment: '#content', snap: true, stack: '#cardPile div', cursor: 'move',
start: function (e) {
},
stop: function (e) {
setTimeout(function () {
handleNewClicks()
}, 1);
}
})
In addition, this function binds events to the cells. When you bind the events to the cells multiple times, they are getting called more than once. You only need to run handleNewClicks() once when initializing the alchemy lab.
function handleNewClicks() {
$(".pro_cell_3").click(function () {
var currentUp = parseInt($(this).parent().find('.pro_cell_2').text(), 10);
var maxUp = 10;
if (currentUp == maxUp) {
$(this).parent().find('.pro_cell_2').text("1");
} else {
$(this).parent().find('.pro_cell_2').text(currentUp + 1);
}
});
$(".pro_cell_4").click(function () {
var currentUp = parseInt($(this).parent().find('.pro_cell_2').text(), 10);
var maxUp = 10;
if ((currentUp - 1) == 0) {
$(this).parent().find('.pro_cell_2').text(maxUp);
} else {
$(this).parent().find('.pro_cell_2').text(currentUp - 1);
}
});
$(".up_cell_3").click(function () {
var currentUp = parseInt($(this).parent().find('.up_cell_2').text(), 10);
var maxUp = parseInt($(this).parent().find('.up_cell_2').attr("max"), 10);
var className = $(this).parent().parent().attr("class");
className = className.replace("ui-draggable ", "");
if (currentUp == maxUp) {
$(this).parent().find('.up_cell_2').text("1");
$(this).parent().parent().css({ 'background-image': 'url(images/' + className + '_1.png)' });
} else {
$(this).parent().find('.up_cell_2').text(currentUp + 1);
$(this).parent().parent().css({ 'background-image': 'url(images/' + className + '_' + (currentUp + 1) + '.png)' });
}
});
$(".up_cell_4").click(function () {
var currentUp = parseInt($(this).parent().find('.up_cell_2').text(), 10);
var maxUp = parseInt($(this).parent().find('.up_cell_2').attr("max"), 10);
var className = $(this).parent().parent().attr("class");
className = className.replace("ui-draggable ", "");
if ((currentUp - 1) == 0) {
$(this).parent().find('.up_cell_2').text(maxUp);
$(this).parent().parent().css({ 'background-image': 'url(images/' + className + '_' + maxUp + '.png)' });
} else {
$(this).parent().find('.up_cell_2').text(currentUp - 1);
$(this).parent().parent().css({ 'background-image': 'url(images/' + className + '_' + (currentUp - 1) + '.png)' });
}
});
}
Basically, to fix this, you could change the following function to what I have below:
$(".nav_alchemy_lab").click(function () {
proCoding();
upCoding();
newLab.appendChild(proWrap);
newLab.appendChild(upWrap);
$(newLab).attr('class', 'ui-draggable alchemy_lab').appendTo('#cardPile').css({ 'top': pos_top, 'left': pos_left, 'background-image': 'url(images/alchemy_lab_1.png)' }).draggable({
containment: '#content', snap: true, stack: '#cardPile div', cursor: 'move'
});
handleNewClicks()
});
This is all untested.

Categories