Draggable object doesn't recognize target Javascript Jquery - javascript

I'm new to Javascript, but I customized a code from an array of number to an array of letters in which I want to recognize the target in order to complete the game.
The error in the code is that its drops to any of the targets, that means that it doesn't recognize the respectively target.
The original code
and the code that I customized.
var correctCards = 0;
$(init);
function init() {
// Hide the success message
$('#successMessage').hide();
$('#successMessage').css({
left: '580px',
top: '250px',
width: 0,
height: 0
});
// Reset the game
correctCards = 0;
$('#vocalPile').html('');
$('#vocalSlots').html('');
// Create the pile of shuffled cards
var vocales = ["a", 'e','i' , 'o', 'u'];
vocales.sort( function() { return Math.random() - .5 } );
for ( var i=0; i<5; i++ ) {
$('<div>' + vocales[i] + '</div>')
.data('vocal', vocales[i])
.attr('id', 'vocal'+vocales[i])
.appendTo('#vocalPile')
.draggable({
containment: '#content',
stack: '#vocalPile div',
cursor: 'move',
revert: true
});
}
// Create the card slots
var words = ['a', 'e', 'i', 'o', 'u'];
for (var i = 1; i <= 5; i++ ) {
$('<div>' + words[i-1] + '</div>')
.data('vocal', i)
.appendTo('#vocalSlots')
.droppable({
accept: '#vocalPile div',
hoverClass: 'hovered',
drop: handleCardDrop
});
}
}
function handleCardDrop( event, ui ) {
var slotVocal = $(this).data('vocales');
var cardVocal = ui.draggable.data('vocales');
// If the card was dropped to the correct slot,
// change the card colour, position it directly
// on top of the slot, and prevent it being dragged
// again
if ( slotVocal == cardVocal ) {
ui.draggable.addClass('correct');
ui.draggable.draggable('disable');
$(this).droppable('disable');
ui.draggable.position({ of: $(this), my: 'left top', at: 'left top' });
ui.draggable.draggable('option', 'revert', false);
correctCards++;
}
// If all the cards have been placed correctly then display a message
// and reset the cards for another go
if (correctCards == 5) {
$('#successMessage').show();
$('#successMessage').animate( {
left: '380px',
top: '200px',
width: '400px',
height: '100px',
opacity: 1
});
}
}
I think that there's an error in the parameters that is passing through the functions. But I dont know how to change them in the if ==.
Thanks :)
PS. Is an array of vowels not number the one that I want to implement.

You have an error in
in create card slots:
$('<div>' + words[i-1] + '</div>')
.data( 'vocal',words[i-1])...
use words array
in handleCardDrop function fix data attribute to vocal not vocales as in your fiddle
function handleCardDrop( event, ui ) {
var slotVocal = $(this).data( 'vocal' );
var cardVocal = ui.draggable.data( 'vocal' );
working fiddle

Related

Matching drag'n'drop elements

I am trying to understand the drag and drop mechanics in JS and HTML. I have used some code I have found and am trying to adapt it into something different. I want the cardPile to include pictures, with names such as "motherboard.jpg" etc, and match it to the cardSlots with similar names. How could I do that? I tried changing the numeric values in cardPile into strings, but it does not work with dropping.
Any advice? (Sorry, it is my first time on StackOverflow :') )
JS code:
var correctCards = 0;
$( init );
function init() {
// Hide the success message
$('#successMessage').hide();
$('#successMessage').css( {
left: '580px',
top: '250px',
width: 0,
height: 0
} );
// Reset the game
correctCards = 0;
$('#cardPile').html( '' );
$('#cardSlots').html( '' );
// Create the pile of shuffled cards
var numbers = [ 1, "a", "b", "c", "d", "e", "f", "g", "h", "i" ];
numbers.sort( function() { return Math.random() - .5 } );
for ( var i=0; i<10; i++ ) {
$('<div>' + numbers[i] + '</div>').data( 'number', numbers[i] ).attr( 'id', 'card'+numbers[i] ).appendTo( '#cardPile' ).draggable( {
containment: '#content',
stack: '#cardPile div',
cursor: 'move',
revert: true
} );
}
// Create the card slots
var words = [ 'Motherboard', 'RAM', 'GPU', 'CPU', 'I/O', 'Power supply', 'Oprical Drive', 'HDD', 'SSD', 'Expansion slots' ];
for ( var i=1; i<=10; i++ ) {
$('<div>' + words[i-1] + '</div>').data( 'number', i ).appendTo( '#cardSlots' ).droppable( {
accept: '#cardPile div',
hoverClass: 'hovered',
drop: handleCardDrop
} );
}
}
function handleCardDrop( event, ui ) {
var slotNumber = $(this).data( 'number' );
var cardNumber = ui.draggable.data( 'number' );
// If the card was dropped to the correct slot,
// change the card colour, position it directly
// on top of the slot, and prevent it being dragged
// again
if ( slotNumber == cardNumber ) {
ui.draggable.addClass( 'correct' );
ui.draggable.draggable( 'disable' );
$(this).droppable( 'disable' );
ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
ui.draggable.draggable( 'option', 'revert', false );
correctCards++;
}
// If all the cards have been placed correctly then display a message
// and reset the cards for another go
if ( correctCards == 10 ) {
$('#successMessage').show();
$('#successMessage').animate( {
left: '380px',
top: '200px',
width: '400px',
height: '100px',
opacity: 1
} );
}
}

Multiple (but not all) card slots

Trying to recreate a game in which cards are sorted into card slots. I can make it so that card 'a' goes into the first card slot 'Even', but I want to make it so that card 'a' can also go in the the second card slot 'Even.' Similarly, I want card 'b' to be able to go into either 'Even' slot. Ditto cards 'c' and 'd' for either 'Odd' slot and 'e' and 'f' for the either 'Even and Odd' slots. Any ideas?
// Create the pile of shuffled cards
var equations = [];
equations [ 0 ] = {x:1, y:'a'};
equations [ 1 ] = {x:2, y:'b'};
equations [ 2 ] = {x:3, y:'c'};
equations [ 3 ] = {x:4, y:'d'};
equations [ 4 ] = {x:5, y:'e'};
equations [ 5 ] = {x:6, y:'f'};
equations.sort( function() { return Math.random() - .4 } );
for ( var i=0; i<6; i++ ) {
$('<div>' + equations[i].y + '</div>').data( 'number', equations[i].x ).attr( 'id', 'card'+equations[i].x ).appendTo( '#cardPile' ).draggable( {
containment: '#content',
stack: '#cardPile div',
cursor: 'move',
revert: true
} );
}
// Create the card slots
var words = [ 'Even', 'Even', 'Odd)', 'Odd', 'Even + Odd', 'Even + Odd' ];
for ( var i=1; i<=6; i++ ) {
$('<div>' + words[i-1] + '</div>').data( 'number', i ).appendTo( '#cardSlots' ).droppable( {
accept: '#cardPile div',
hoverClass: 'hovered',
drop: handleCardDrop
} );
}
}
function handleCardDrop( event, ui ) {
var slotNumber = $(this).data( 'number' );
var cardNumber = ui.draggable.data( 'number' );
// If the card was dropped to the correct slot,
// change the card colour, position it directly
// on top of the slot, and prevent it being dragged
// again
if ( slotNumber == cardNumber) {
ui.draggable.addClass( 'correct' );
ui.draggable.draggable( 'disable' );
$(this).droppable( 'disable' );
ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
ui.draggable.draggable( 'option', 'revert', false );
correctCards++;
}
// If all the cards have been placed correctly then display a message
// and reset the cards for another go
if ( correctCards == 6) {
$('#successMessage').show();
$('#successMessage').animate( {
left: '430px',
top: '150px',
width: '400px',
height: '180px',
opacity: 1
} );
}
}
});
Right now you have a one-to-one relationship between cards and slots, but it sounds like you want a one-to-many relationship.
So first thing you need to do is define the correct answer for each of your equations by adding a third value.
equations [ 0 ] = {x:1, y:'a', correct: 'Even'};
(You can make this an array if you want multiple correct answers.)
Next, you need to add this answer to the card's data.
.data( 'correct', equations[i].correct )
And finally check for the answer when you handle the drop
var slotAnswer = $(this).text();
var cardAnswer = ui.draggable.data( 'correct' );
if ( slotAnswer == cardAnswer) {
It might be better to store the slot answer in the data instead of just the text.
Also, you have a typo in the slot name of Odd)

Jquery splitter plugin getting error too much recursion

I am using this jquery splitter plugin located here: http://methvin.com/splitter/
It is working fine with the version of jquery I am using until I enable the resizeToWidth property then it is giving me the error: too much recursion.
Here is a link to a demo I created on jsfiddle: http://jsfiddle.net/S97rv/4/
Iv looked at the plugin code but im not a javascript expert and don't want to mess with it to much.
Can anybody see a solution to this error?
Here is the plugin code but probably better just looking at the jsfiddle link:
;(function($){
$.fn.splitter = function(args){
args = args || {};
return this.each(function() {
var zombie; // left-behind splitbar for outline resizes
function startSplitMouse(evt) {
if ( opts.outline )
zombie = zombie || bar.clone(false).insertAfter(A);
panes.css("-webkit-user-select", "none"); // Safari selects A/B text on a move
bar.addClass(opts.activeClass);
A._posSplit = A[0][opts.pxSplit] - evt[opts.eventPos];
$(document)
.bind("mousemove", doSplitMouse)
.bind("mouseup", endSplitMouse);
}
function doSplitMouse(evt) {
var newPos = A._posSplit+evt[opts.eventPos];
if ( opts.outline ) {
newPos = Math.max(0, Math.min(newPos, splitter._DA - bar._DA));
bar.css(opts.origin, newPos);
} else
resplit(newPos);
}
function endSplitMouse(evt) {
bar.removeClass(opts.activeClass);
var newPos = A._posSplit+evt[opts.eventPos];
if ( opts.outline ) {
zombie.remove(); zombie = null;
resplit(newPos);
}
panes.css("-webkit-user-select", "text"); // let Safari select text again
$(document)
.unbind("mousemove", doSplitMouse)
.unbind("mouseup", endSplitMouse);
}
function resplit(newPos) {
// Constrain new splitbar position to fit pane size limits
newPos = Math.max(A._min, splitter._DA - B._max,
Math.min(newPos, A._max, splitter._DA - bar._DA - B._min));
// Resize/position the two panes
bar._DA = bar[0][opts.pxSplit]; // bar size may change during dock
bar.css(opts.origin, newPos).css(opts.fixed, splitter._DF);
A.css(opts.origin, 0).css(opts.split, newPos).css(opts.fixed, splitter._DF);
B.css(opts.origin, newPos+bar._DA)
.css(opts.split, splitter._DA-bar._DA-newPos).css(opts.fixed, splitter._DF);
// IE fires resize for us; all others pay cash
if ( !$.browser.msie )
panes.trigger("resize");
}
function dimSum(jq, dims) {
// Opera returns -1 for missing min/max width, turn into 0
var sum = 0;
for ( var i=1; i < arguments.length; i++ )
sum += Math.max(parseInt(jq.css(arguments[i])) || 0, 0);
return sum;
}
// Determine settings based on incoming opts, element classes, and defaults
var vh = (args.splitHorizontal? 'h' : args.splitVertical? 'v' : args.type) || 'v';
var opts = $.extend({
activeClass: 'active', // class name for active splitter
pxPerKey: 8, // splitter px moved per keypress
tabIndex: 0, // tab order indicator
accessKey: '' // accessKey for splitbar
},{
v: { // Vertical splitters:
keyLeft: 39, keyRight: 37, cursor: "e-resize",
splitbarClass: "vsplitbar", outlineClass: "voutline",
type: 'v', eventPos: "pageX", origin: "left",
split: "width", pxSplit: "offsetWidth", side1: "Left", side2: "Right",
fixed: "height", pxFixed: "offsetHeight", side3: "Top", side4: "Bottom"
},
h: { // Horizontal splitters:
keyTop: 40, keyBottom: 38, cursor: "n-resize",
splitbarClass: "hsplitbar", outlineClass: "houtline",
type: 'h', eventPos: "pageY", origin: "top",
split: "height", pxSplit: "offsetHeight", side1: "Top", side2: "Bottom",
fixed: "width", pxFixed: "offsetWidth", side3: "Left", side4: "Right"
}
}[vh], args);
// Create jQuery object closures for splitter and both panes
var splitter = $(this).css({position: "relative"});
var panes = $(">*", splitter[0]).css({
position: "absolute", // positioned inside splitter container
"z-index": "1", // splitbar is positioned above
"-moz-outline-style": "none" // don't show dotted outline
});
var A = $(panes[0]); // left or top
var B = $(panes[1]); // right or bottom
// Focuser element, provides keyboard support; title is shown by Opera accessKeys
var focuser = $('')
.attr({accessKey: opts.accessKey, tabIndex: opts.tabIndex, title: opts.splitbarClass})
.bind($.browser.opera?"click":"focus", function(){ this.focus(); bar.addClass(opts.activeClass) })
.bind("keydown", function(e){
var key = e.which || e.keyCode;
var dir = key==opts["key"+opts.side1]? 1 : key==opts["key"+opts.side2]? -1 : 0;
if ( dir )
resplit(A[0][opts.pxSplit]+dir*opts.pxPerKey, false);
})
.bind("blur", function(){ bar.removeClass(opts.activeClass) });
// Splitbar element, can be already in the doc or we create one
var bar = $(panes[2] || '<div></div>')
.insertAfter(A).css("z-index", "100").append(focuser)
.attr({"class": opts.splitbarClass, unselectable: "on"})
.css({position: "absolute", "user-select": "none", "-webkit-user-select": "none",
"-khtml-user-select": "none", "-moz-user-select": "none"})
.bind("mousedown", startSplitMouse);
// Use our cursor unless the style specifies a non-default cursor
if ( /^(auto|default|)$/.test(bar.css("cursor")) )
bar.css("cursor", opts.cursor);
// Cache several dimensions for speed, rather than re-querying constantly
bar._DA = bar[0][opts.pxSplit];
splitter._PBF = $.boxModel? dimSum(splitter, "border"+opts.side3+"Width", "border"+opts.side4+"Width") : 0;
splitter._PBA = $.boxModel? dimSum(splitter, "border"+opts.side1+"Width", "border"+opts.side2+"Width") : 0;
A._pane = opts.side1;
B._pane = opts.side2;
$.each([A,B], function(){
this._min = opts["min"+this._pane] || dimSum(this, "min-"+opts.split);
this._max = opts["max"+this._pane] || dimSum(this, "max-"+opts.split) || 9999;
this._init = opts["size"+this._pane]===true ?
parseInt($.curCSS(this[0],opts.split)) : opts["size"+this._pane];
});
// Determine initial position, get from cookie if specified
var initPos = A._init;
if ( !isNaN(B._init) ) // recalc initial B size as an offset from the top or left side
initPos = splitter[0][opts.pxSplit] - splitter._PBA - B._init - bar._DA;
if ( opts.cookie ) {
if ( !$.cookie )
alert('jQuery.splitter(): jQuery cookie plugin required');
var ckpos = parseInt($.cookie(opts.cookie));
if ( !isNaN(ckpos) )
initPos = ckpos;
$(window).bind("unload", function(){
var state = String(bar.css(opts.origin)); // current location of splitbar
$.cookie(opts.cookie, state, {expires: opts.cookieExpires || 365,
path: opts.cookiePath || document.location.pathname});
});
}
if ( isNaN(initPos) ) // King Solomon's algorithm
initPos = Math.round((splitter[0][opts.pxSplit] - splitter._PBA - bar._DA)/2);
// Resize event propagation and splitter sizing
if ( opts.anchorToWindow ) {
// Account for margin or border on the splitter container and enforce min height
splitter._hadjust = dimSum(splitter, "borderTopWidth", "borderBottomWidth", "marginBottom");
splitter._hmin = Math.max(dimSum(splitter, "minHeight"), 20);
$(window).bind("resize", function(){
var top = splitter.offset().top;
var wh = $(window).height();
splitter.css("height", Math.max(wh-top-splitter._hadjust, splitter._hmin)+"px");
if ( !$.browser.msie ) splitter.trigger("resize");
}).trigger("resize");
}
else if ( opts.resizeToWidth && !$.browser.msie )
$(window).bind("resize", function(){
splitter.trigger("resize");
});
// Resize event handler; triggered immediately to set initial position
splitter.bind("resize", function(e, size){
// Custom events bubble in jQuery 1.3; don't get into a Yo Dawg
if ( e.target != this ) return;
// Determine new width/height of splitter container
splitter._DF = splitter[0][opts.pxFixed] - splitter._PBF;
splitter._DA = splitter[0][opts.pxSplit] - splitter._PBA;
// Bail if splitter isn't visible or content isn't there yet
if ( splitter._DF <= 0 || splitter._DA <= 0 ) return;
// Re-divvy the adjustable dimension; maintain size of the preferred pane
resplit(!isNaN(size)? size : (!(opts.sizeRight||opts.sizeBottom)? A[0][opts.pxSplit] :
splitter._DA-B[0][opts.pxSplit]-bar._DA));
}).trigger("resize" , [initPos]);
});
};
})(jQuery);
The plugin you are using is based on a old jQuery version. For some reason, an infinite recursion was introduced by jQuery 1.6, probably due to event bubbling. It seems like a resize event triggered on a specific DOM element follow the event propagation path, all the way to document.
In the resize event handler, you can add a test to prevent recursion:
$(window).bind("resize", function (e) {
if (e.target === window) { splitter.trigger('resize'); }
});
That works, at least in Chrome and Firefox.
Using jQuery Migrate plugin will allow you to use jQuery 1.9 and even 2.0; but relying on browser specific behavior is generally a bad practice. You may have a look at this splitter.js fork, which already fixes your infinite recursion issue, using the same test as above.

Autoscrolling slide javascript

I have This javascript code for a slider that I downloaded , and can't figure out how to make it auto scrolling !!
I actually downloaded this code from http://tympanus.net/Tutorials/FullscreenSlitSlider/index2.html
It actually don't contain a next button so i can add an interval like the other sliders :(
$(function() {
var Page = (function() {
var $nav = $( '#nav-dots > span' ),
slitslider = $( '#slider' ).slitslider( {
onBeforeChange : function( slide, pos ) {
$nav.removeClass( 'nav-dot-current' );
$nav.eq( pos ).addClass( 'nav-dot-current' );
}
} ),
init = function() {
initEvents();
setInterval(initEvents,1000);
},
initEvents = function() {
$nav.each( function( i ) {
$( this ).on( 'click', function( event ) {
var $dot = $( this );
if( !slitslider.isActive() ) {
$nav.removeClass( 'nav-dot-current' );
$dot.addClass( 'nav-dot-current' );
}
slitslider.jump( i + 1 );
return false;
} );
} );
};
return { init : init };
})();
Page.init();
});
Like it says in the docs (Google is helpful):
slitslider = $( '#slider' ).slitslider({
autoplay : true
});
should do it.
If you don't want to read the whole thing, here's a short list of common config options:
$.Slitslider.defaults = {
// transitions speed
speed : 800,
// if true the item's slices will also animate the opacity value
optOpacity : false,
// amount (%) to translate both slices - adjust as necessary
translateFactor : 230,
// maximum possible angle
maxAngle : 25,
// maximum possible scale
maxScale : 2,
// slideshow on / off
autoplay : false,
// keyboard navigation
keyboard : true,
// time between transitions
interval : 4000,
// callbacks
onBeforeChange : function( slide, idx ) { return false; },
onAfterChange : function( slide, idx ) { return false; }
};

How to add a new item to the end of the list using jQuery?

I have this function for adding a new item to the beginning of the list and removing the last one:
function addItem(id, text){
var el = $('#' + id);
var w = el.width();
el.css({
width: w,
overflow: 'hidden'
});
var ulPaddingLeft = parseInt(el.css('padding-left'));
var ulPaddingRight = parseInt(el.css('padding-right'));
el.prepend('<li>' + text + '</li>');
var first = $('li:first', el);
var last = $('li:last', el);
var fow = first.outerWidth();
var widthDiff = fow - last.outerWidth();
var oldMarginLeft = first.css('margin-Left');
first.css({
marginLeft: 0 - fow,
position: 'relative',
left: 0 - ulPaddingLeft
});
last.css('position', 'relative');
el.animate({ width: w + widthDiff }, 1500);
first.animate({ left: 0 }, 250, function() {
first.animate({ marginLeft: oldMarginLeft }, 1000, function() {
last.animate({ left: ulPaddingRight }, 250, function() {
last.remove();
el.css({
width: 'auto',
overflow: 'visible'
});
});
});
});
}
How can I make it work the other way around ? I want to add the item to the end and remove the first and also make it slide the other way around, like right to left.
Take a look at jQuery.append (and jQuery.prepend for beginning of list)
Your code seems really complicated. Simplifying it a little bit might give you something like this:
$("#whateverList").addItem("awesome")
jQuery.fn.addItem = function(text) {
var $li = $("<li>").text(text)
$(this).find("li:first").remove()
$(this).append($li)
}
jQuery plugin syntax is super easy to understand
append() to go to the bottom
var declarations at the top
Good luck!

Categories

Resources