Dragging parent div, while mousedown on draggable child div - javascript

When a div is clicked, fires function, in which, on mousedown, new div is created, and in that new div the clicked one and some others are appended (all of those appended divs are have draggable plugin on them). My question is: how do I drag the new div? As you will notice, I tried using handle, but failed.
var game = this;
var cardOldLocationId;
var tempWraperSelector;
$('#playArea').children().on('mousedown', function(event) {
tempWraperSelector = $('<div id="multipleCardSelector"> </dv>');
$(tempWraperSelector).appendTo('#' + $(event.target).parent().parent().attr('id'));
cardOldLocationId = $(event.target).parent().parent().attr('id');
var selectedCardIndex;
var cardsToAppend = [];
var pressedRowLenght = game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]].length;
for (var i = 0; i < game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]].length; i++) {
if (game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]][i].Taskai + "_" + game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]][i].Simbolis === $(event.target).attr('id')) {
selectedCardIndex = i;
break;
}
}
for (var j = selectedCardIndex; j < pressedRowLenght; j++) {
var cardSelector = '#' + game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]][j].Taskai + "_" + game.options.rows[$(event.target).parent().parent().attr('id').split('_')[0]][j].Simbolis;
cardsToAppend.push(cardSelector);
}
for (var k = 0; k < cardsToAppend.length; k++) {
$(cardsToAppend[k]).parent().appendTo(tempWraperSelector);
}
$(tempWraperSelector).draggable({
handle: '#' + $(event.target).attr('id')
});
});
$('#playArea').children().on('mouseup', function(event) {
$(tempWraperSelector).children().appendTo('#' + cardOldLocationId);
$(tempWraperSelector).remove();
});

Related

How do i convert a Jquery code to Pure javascript

I am using Bootstrap.
I am not able to figure out how to put this in pure javascript.This will open a div when we click on the accordion.
$(function() {
$("#panelTicketsList .list-group-item").on("click", function() {
$("#panelTicketsList .list-group-item").removeClass('selected');
$(this).addClass('selected');
if ($('#panelTicketsList').hasClass('col-md-12')) {
$('#panelTicketsList').removeClass('col-md-12').addClass('col-md-3');
$('.panelTicketDetail').removeClass('hide');
}
});
});
jsFiddle : https://jsfiddle.net/tqdc6yyL/
var listGroupItems = document.getElementsByClassName('list-group-item');
for (j = 0; j < listGroupItems.length; j++) {
listGroupItems[j].addEventListener("click", function () {
var elements = listGroupItems;
for (i = 0; i < elements.length; i++) {
if (elements[i].className.indexOf("col-md-12") > -1) {
elements[i].className = elements[i].className.replace("col-md-12", "col-md-3");
elements[i].className = elements[i].className.replace("hide", "");
}
}
this.className = this.className + " selected";
});
}
var list = document.getElementById('panelTicketsList');
var items = document.querySelectorAll("#panelTicketsList .list-group-item");
var detail = document.querySelectorAll(".panelTicketDetail");
items.forEach(function(btn){
btn.addEventListener("click", function(){
items.forEach(function(item){ item.classList.remove("selected"); });
this.classList.add("selected");
if(list.classList.contains('col-md-12')) {
list.classList.remove('col-md-12');
list.classList.add('col-md-3');
detail.classList.add("hide");
}
});
If you have to support older browsers like IE8 or IE9, you can't use JS features like forEach or classList. Instead you should use for loop and className.
//Save DOM query in variable for reuse
var panelTicketsList = document.getElementById('panelTicketsList');
var panelTicketsDetails = document.getElementsByClassName('panelTicketDetail');
var listGroupItems = panelTicketsList.getElementsByClassName('list-group-item');
//go through all of the listGroupItems and set click listener
for (var i = 0; i < listGroupItems.length - 1; i++) {
listGroupItems[i].addEventListener("click", function() {
//On click, go through all of listGroupItems and remove selected class
for (var j = 0; j < listGroupItems.length - 1; j++) {
listGroupItems[j].className = listGroupItems[j].className.replace('selected', '');
}
//Add selected class for clicked element
listGroupItems[i].className += 'selected';
//test if main element has class col-md-12
if (panelTicketsList.className.indexOf("col-md-12") > -1) {
//replace clas col-md-12 with col-md-3
panelTicketsList.className = panelTicketsList.className.replace('col-md-12', 'col-md-3');
//go through all of the panelTicketDetails and remove hide class
for (var k = 0; k < panelTicketsDetails.length - 1; k++) {
panelTicketsDetails[k].className = panelTicketsDetails[k].className.replace('hide', '');
}
}
});
}

Change script from start onclick to onload

I'm looking to change this script so that the animation starts once the page has loaded instead of when the div is clicked on.
Any suggestions on how I could do this would be much appreciated.
Here is the JS
$(document).ready(function() {
$(".marqueeElement").last().addClass("last");
$(".mholder").each(function() {
var i = 0;
$(this).find(".marqueeElement").each(function() {
var $this = $(this);
$this.css("top", i);
i += $this.height();
});
});
$('.mholder').click(function() {
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
});
});
function doScroll($ele) {
var top = parseInt($ele.css("top"));
if (top < -60) { //bit arbitrary!
var $lastEle = $ele.closest('.mholder').find(".last");
$lastEle.removeClass("last");
$ele.addClass("last");
var top = (parseInt($lastEle.css("top")) + $lastEle.height());
$ele.css("top", top);
}
$ele.animate({
top: (parseInt(top) - 60)
}, 80, 'linear', function() {
doScroll($(this))
});
}
Just move the code inside the .ready() event.
$(document).ready(function() {
$(".marqueeElement").last().addClass("last");
$(".mholder").each(function() {
var i = 0;
$(this).find(".marqueeElement").each(function() {
var $this = $(this);
$this.css("top", i);
i += $this.height();
});
});
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
});
Assuming '.mholder' is the selector for your div, just get rid of the click handler - i.e. change from:
$('.mholder').click(function() {
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
});
to
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
the most easiest way is to put at the end of the on ready function the following (after you bind the click event):
$('.mholder').click()

Passing an argument to a event listener from dynamically created buttons

I'm dynamically creating 3 buttons. How can I pass an argument tohandlerX?
So basically I want the values in the category Array to be passed on to the handlerX eventListener.
Example:
When myBtn1 is clicked, I want the alert to be "fur_",
When myBtn3 is clicked, I want the alert to be "fas_"
var btns = '';
var category = ["fur_", "fts_", "fas_"];
for (i = 1; i < category.length; i++) {
btns += '<button type="button" class=' + category[i] + ' id= "myBtn' + i + '">.....</button>';
}
var div = document.getElementById('div');
div.innerHTML = btns;
var handlerX = function () {
alert('Clicked'); //get value from the 'category' Array
};
var buttons = div.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', handlerX, false);
}
The answers given so far are good and should solve your problem. Just thought I'd add this one because I think it's a solution more in line with what you were asking for: Make your handlerX return a function like so:
var handlerX = function (param) {
return function() {alert(param);};
};
var buttons = div.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', handlerX(category[i]), false);
}
Edit: Here's a Fiddle
If you're willing to extract it from the class attribute, then:
var handlerX = function () {
alert(this.getAttribute('class'));
};
Or you better associate it with some data- attribute. For example:
for (i = 1; i < category.length; i++) {
btns += '<button type="button" data-category="' + category[i] + '" class=' + category[i] + ' id= "myBtn' + i + '">.....</button>';
}
Then:
var handlerX = function () {
alert(this.getAttribute('data-category'));
};
See Fiddle
EDIT:
then i would reccomend adding an attibute: data-category="fur_" for example, and access that from your event handler:
this.getAttribute('data-category')
in hadlerX there is a "this" that is the element that was clicked. You can access its getAttribute("class") to get the class EDIT:this, not self
var fragment = document.createDocumentFragment(),
categories = ["fur_", "fts_", "fas_"],
btn;
function onClickBtn() {
alert(this.getAttribute("data-category"));
}
for (var i = 0; i < categories.length; i++) {
btn = document.createElement("button");
btn.id = "myBtn" + string(i);
btn.setAttribute("data-category", category[i]);
btn.addEventListener("click", onClickBtn);
fragment.appendChild(btn);
}
var div = document.getElementById('div');
div.appendChild(fragment);

id for each element showing undefined or 0 not being assigning different id's

I'm trying to assign a id to each link in my list like this,
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
$('#citations').append('<li><a href="' + link + '" id="num" + j>' +
json[j].title + '</a></li>');
alert($('a').attr('id'));
}
it keeps giving me undefined or 0? Should I use $.each outside of the for loop instead?
I was trying to use the for loop for two purposes but maybe that's not such a great idea?
*EDIT***
If I put my for loop inside of a function like,
// Loop function for each section
var loopSection = function(start, stop) {
// Http setup for all links
var linkBase = "http://www.sciencebase.gov/catalog/item/";
// Link for citation information
var link = "";
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
var $anchor = $("<a>", {
href: link,
id: "id" + j,
text: json[j].title
})
// .parent() will get the <li> that was just created and append to the first citation
element
$anchor.appendTo("<li>").parent().appendTo("#citations");
}
}
I'm not able to access the id from outside of the function
$('#citations').on('click', function (e) {
e.preventDefault();
var print = ($(this).attr('id'));
alert(print);
});
This form is much cleaner:
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
$("<a>", {
href: link,
id:'num' + j,
text: json[j].title
}).appendTo("<li>")
.parent() // get the <li> we just made
.appendTo("#citations");
}
If you want a reference to the anchor tag you created, do this:
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
var $anchor = $("<a>", {
href: link,
id:'num' + j,
text: json[j].title
});
$anchor.appendTo("<li>").parent().appendTo("#citations");
}
You have a syntax error in your code (id="num" + j..)
However,You should do this by the code (avoiding syntax error and giving a better performance)
for (var j = start; j < stop; j++)
{
var link = linkBase + json[j].relatedItemId;
$('#citations').append($(document.createElement('li'))
.append($(document.createElement('a'))
.attr('href', link)
.attr('id', 'num' + j)
.html(json[j].title)));
}
Agree with the answer from Schmiddty but, for the sake of completeness
for (var j = 0; j < 10; j++) {
var link = "someLink.htm";
$('#citations').append('<li>'+ 'click here' + '</li>');
alert($('#citations a:last').attr('id'));
}
I've only changed your variable to make it work on its own on this fiddle as a demo

Adding a class to before and after links in a for statement using JavaScript?

I have a list of links in a UL. Can someone give me an example of how to detect what the index is of the link that was clicked, then add one class to all the links in LIs before the selected link and a different class to all the links in LIs after the selected link?
var ul = document.getElementById('your-ul'),
li = ul.getElementsByTagName('li');
var iterateLi = function(fn) {
for (var i = 0, length = li.length; i < length; i++) {
fn.call(li[i], i);
}
};
iterateLi(function(index) {
var thisIndex = index,
thisLi = this;
this.onclick = function(index) {
iterateLi(function(index) {
var classes = ['before', 'selected', 'after'],
addClass;
if (index < thisIndex) {
addClass = classes[0];
} else if (index == thisIndex) {
addClass = classes[1];
} else {
addClass = classes[2];
}
for (var i = 0, length = classes.length; i < length; i++) {
}
var className = this.className;
if (className) {
var regex = new RegExp('(?:' + classes.join('|') + ')', 'g');
className = className.replace(regex, '');
console.log(regex, className)
}
this.className = className + ' ' + addClass;
});
};
});
jsFiddle.

Categories