jQuery draggable applying multiple clicks after drag - javascript

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.

Related

Image Resizer - issue to drag an image into a div

I want to make a little program where we can :
- Drag and drop an image into a Div (from desktop to the div of the web page)
- Drag the image into this div
- Zoom in and zoom out whit the mouse wheel.
what id did is drag and drop an image and its work..
i set an id of the image in my Javascript code and in my console i see that the image receive the id='movable'.. But when i test that in my browser the image doesnt move with my mouse.
Here is my Javascript Code :
//Creation d'un DIV dynamique
monDiv = document.createElement("div");
monDiv.id = 'dropZone';
monDiv.innerHTML = '<h4>Glissez deposez une image</h4>';
document.body.appendChild(monDiv);
//Drag And Drop
(function(window) {
function triggerCallback(e, callback) {
if(!callback || typeof callback !== 'function') {
return;
}
var files;
if(e.dataTransfer) {
files = e.dataTransfer.files;
} else if(e.target) {
files = e.target.files;
}
callback.call(null, files);
}
function makeDroppable(ele, callback) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('multiple', true);
input.style.display = 'none';
input.addEventListener('change', function(e) {
triggerCallback(e, callback);
});
ele.appendChild(input);
ele.addEventListener('dragover', function(e) {
e.preventDefault();
e.stopPropagation();
ele.classList.add('dragover');
});
ele.addEventListener('dragleave', function(e) {
e.preventDefault();
e.stopPropagation();
ele.classList.remove('dragover');
});
ele.addEventListener('drop', function(e) {
e.preventDefault();
e.stopPropagation();
ele.classList.remove('dragover');
triggerCallback(e, callback);
});
}
window.makeDroppable = makeDroppable;
})(this);
(function(window) {
makeDroppable(window.document.querySelector('#dropZone'), function(files) {
console.log(files);
var output = document.querySelector('#dropZone');
output.innerHTML = '';
for(var i=0; i<files.length; i++) {
if(files[i].type.indexOf('image/') === 0) {
output.innerHTML += '<img src="' + URL.createObjectURL(files[i]) + '" id="movable" />';
}
}
});
})(this);
//DRAG
$('#movable').on('mousedown', function (e) {
$(this).addClass('active');
var oTop = e.pageY - $('.active').offset().top;
var oLeft = e.pageX - $('.active').offset().left;
$(this).parents().on('mousemove', function (e) {
$('.active').offset({
top: e.pageY - oTop,
left: e.pageX - oLeft
});
});
$(this).on('mouseup', function () {
$(this).removeClass('active');
});
return false;
});
Increase image ration on scroll up and decrease it on scroll down.
zoomIn: function ()
{
image.ratio*=1.1;
createBackground();
},
zoomOut: function ()
{
image.ratio*=0.9;
createBackground();
}
createBackground = function()
{
var w = parseInt(image.width)*image.ratio;
var h = parseInt(image.height)*image.ratio;
//Element in which image is available
var pw = (el.clientWidth - w) / 2;
var ph = (el.clientHeight - h) / 2;
el.setAttribute('style',
'background-image: url(' +image.src + '); ' +
'background-size: ' + w +'px ' + h + 'px; ' +
'background-position: ' + pw + 'px ' + ph + 'px; ' +
'background-repeat: no-repeat');
},
I just figured out.. I place my jQuery code inside the makeDroppable function and the image move inside my div and add overflow:hidden in my css
(function(window) {
makeDroppable(window.document.querySelector('#dropZone'), function(files) {
console.log(files);
var output = document.querySelector('#dropZone');
output.innerHTML = '';
for(var i=0; i<files.length; i++) {
if(files[i].type.indexOf('image/') === 0) {
output.innerHTML += '<img src="' + URL.createObjectURL(files[i]) + '" id="movable" />';
//DRAG
$( "#movable" ).draggable();
}
}
});
})(this);

I'm not sure why my click event won't work

I'm trying to add a click event to .user that will change the background color of the entire page to green. I'm very new to jQuery, but the code looks right to me. When I click the .users button, nothing happens. Anyone have any ideas?
$(document).ready(function() {
var $body = $('body')
/*$body.html('');*/
// var currentView = "Twittler Feed"
var currentView = $('<p>Twittler Feed</p>');
var refreshTweet = function() {
var index = streams.home.length - 1;
var endInd = index - 10;
while (index >= endInd) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweets"><p class="posted-by"><button class="user">#' +
tweet.user + '</button><p class="message">' + tweet.message +
'</p><p class="time">' + /*$.timeago(tweet.created_at)*/ tweet.created_at + '</p></div>');
currentView.appendTo('#sidebar')
$tweet.appendTo($body);
index -= 1;
}
}
refreshTweet();
$('.refresh').on('click', function() {
if (document.getElementsByClassName('tweets')) {
$('.tweets').remove();
}
var result = refreshTweet();
$body.prepend(result);
})
$('.user').on('click', 'button', function() {
currentView = this.user
$('body').css('background-color', 'green');
});
});

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;
}
});

Ajax Code that loads images on click next and previous for any kind of image silder that has huge no of Images using jsp

I have one slider that works perfectly ..... but the images are loaded at the time of page load ...
I want to load the images on click because I have lot of images to display so I can't load it my homepage because the page takes time to load so I have to use Ajax that loads one image
and and append it to my list
can any body help me how to do it ...
here is the code .. its working ..
the java script part
(function($){
$.fn.imageSlider = function(options) {
var options = $.extend({
leftBtn: '.leftBtn',
rightBtn: '.rightBtn',
visible: 3,
autoPlay: false, // true or false
autoPlayDelay: 10 // delay in seconds
}, options);
var make = function() {
$(this).css('overflow', 'hidden');
var thisWidth = $(this).width();
var mod = thisWidth % options.visible;
if (mod) {
$(this).width(thisWidth - mod); // to prevent bugs while scrolling to the end of slider
}
var el = $(this).children('ul');
el.css({
position: 'relative',
left: '0'
});
var leftBtn = $(options.leftBtn), rightBtn = $(options.rightBtn);
var sliderFirst = el.children('li').slice(0, options.visible);
var tmp = '';
sliderFirst.each(function(){
tmp = tmp + '<li>' + $(this).html() + '</li>';
});
sliderFirst = tmp;
var sliderLast = el.children('li').slice(-options.visible);
tmp = '';
sliderLast.each(function(){
tmp = tmp + '<li>' + $(this).html() + '</li>';
});
sliderLast = tmp;
var elRealQuant = el.children('li').length;
el.append(sliderFirst);
el.prepend(sliderLast);
var elWidth = el.width()/options.visible;
el.children('li').css({
float: 'left',
width: elWidth
});
var elQuant = el.children('li').length;
el.width(elWidth * elQuant);
el.css('left', '-' + elWidth * options.visible + 'px');
function disableButtons() {
leftBtn.addClass('inactive');
rightBtn.addClass('inactive');
}
function enableButtons() {
leftBtn.removeClass('inactive');
rightBtn.removeClass('inactive');
}
leftBtn.click(function(event){
event.preventDefault();
if (!$(this).hasClass('inactive')) {
disableButtons();
el.animate({left: '+=' + elWidth + 'px'}, 400,
function(){
if ($(this).css('left') == '0px') {$(this).css('left', '-' + elWidth * elRealQuant + 'px');}
enableButtons();
}
);
}
return false;
});
rightBtn.click(function(event){
event.preventDefault();
if (!$(this).hasClass('inactive')) {
disableButtons();
el.animate({left: '-=' + elWidth + 'px'}, 400,
function(){
if ($(this).css('left') == '-' + (elWidth * (options.visible + elRealQuant)) + 'px') {$(this).css('left', '-' + elWidth * options.visible + 'px');}
enableButtons();
}
);
}
return false;
});
if (options.autoPlay) {
function aPlay() {
rightBtn.click();
delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
}
var delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
el.hover(
function() {
clearTimeout(delId);
},
function() {
delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
}
);
}
};
return this.each(make);
};
})(jQuery);
here is the html
<div class="slider-wrap">
<div class="slider">
<ul id="imgList" class="sliderList">
<li><img><src></li>
<li><img><src></li>
<li><img><src></li>
<li><img><src></li>
<li><img><src></li>
</ul>
</div>
<img src="/evfimages/prevLogo.png"/>
<img src="/evfimages/nextLogo.png"/>
This is the function that call Js File .
jQuery('.slider').imageSlider({
leftBtn: '.sa-left',
rightBtn: '.sa-right',
visible: 5,
});
And some CSS for formatting
So I have a large no of Images 500 .... so i want to use ajax that loads images on click and append to the current list of images ......
any link or suggestion will be appreciated ......

how to check which image has opacity of 1 in image slider for numbering?

i am working on an image slider here. I am trying to display the current number of image being displayed which has the opacity of 1 which is shown in front.
how can I check for opacity of an image and how an i check it again and again so that when the next image opacity is 1 the image number in Dom is displayed.
here is my code
html
<div id="Fader" class="fader">
<img class="slide" src="images/lounge/full/1.jpg" alt="bgImg" />
<img class="slide" src="images/lounge/full/2.jpg" alt="bgImg" />
<img class="slide" src="images/lounge/full/3.jpg" alt="bgImg" />
</div>
Now suppose I have 2.jpg with opacity 1 after some time how can i check which one has opacity of 1 that's being displayed on top?Thanks.
And here is the js Code
(function ($) {
function prefix(el) {
var prefixes = ["Webkit", "Moz", "O", "ms"];
for (var i = 0; i < prefixes.length; i++) {
if (prefixes[i] + "Transition" in el.style) {
return '-' + prefixes[i].toLowerCase() + '-';
};
};
return "transition" in el.style ? "" : false;
};
var methods = {
init: function (settings) {
return this.each(function () {
var config = {
slideDur: 3000,
fadeDur: 900
};
if (settings) {
$.extend(config, settings);
};
this.config = config;
var $container = $(this),
slideSelector = '.slide',
fading = false,
slideTimer,
activeSlide,
newSlide,
$slides = $container.find(slideSelector),
totalSlides = $slides.length,
$pagerList = $container.find('.pager_list');
prefix = prefix($container[0]);
function animateSlides(activeNdx, newNdx) {
function cleanUp() {
$slides.eq(activeNdx).removeAttr('style');
activeSlide = newNdx;
fading = false;
waitForNext();
};
if (fading || activeNdx == newNdx) {
return false;
};
fading = true;
$pagers.removeClass('active').eq(newSlide).addClass('active');
$slides.eq(activeNdx).css('z-index', 3);
$slides.eq(newNdx).css({
'z-index': 2,
'opacity': 1
});
if (!prefix) {
$slides.eq(activeNdx).animate({ 'opacity': 0 }, config.fadeDur,
function () {
cleanUp();
});
} else {
var styles = {};
styles[prefix + 'transition'] = 'opacity ' + config.fadeDur + 'ms';
styles['opacity'] = 0;
$slides.eq(activeNdx).css(styles);
var fadeTimer = setTimeout(function () {
cleanUp();
}, config.fadeDur);
};
};
function changeSlides(target) {
if (target == 'next') {
newSlide = activeSlide + 1;
if (newSlide > totalSlides - 1) {
newSlide = 0;
}
} else if (target == 'prev') {
newSlide = activeSlide - 1;
if (newSlide < 0) {
newSlide = totalSlides - 1;
};
} else {
newSlide = target;
};
animateSlides(activeSlide, newSlide);
};
function waitForNext() {
slideTimer = setTimeout(function () {
changeSlides('next');
}, config.slideDur);
};
for (var i = 0; i < totalSlides; i++) {
$pagerList
.append('<li class="page" data-target="' + i + '">' + i + '</li>');
};
$container.find('.page').bind('click', function () {
var target = $(this).attr('data-target');
clearTimeout(slideTimer);
changeSlides(target);
});
var $pagers = $pagerList.find('.page');
$slides.eq(0).css('opacity', 1);
$pagers.eq(0).addClass('active');
activeSlide = 0;
waitForNext();
});
}
};
$.fn.easyFader = function (settings) {
return methods.init.apply(this, arguments);
};
})(jQuery);
$(function () {
$('#Fader').easyFader({
slideDur: 6000,
fadeDur: 1000
});
});
The easiest way would be to have a CSS class that has a opacity: 1.0 property, and then determining which slide currently has this class.
Let's say the class is .displayed, then you can find the active slide using $slides.find('.displayed').
And when moving to a new slide, just remove the class property after doing any necessary animations:
$slides.find('.displayed').animate({opacity: 0}).removeClass('.displayed');

Categories