javascript transfer and element from 1 div to another - javascript

I'm trying to do a tag filtering function in the website. The transferring from one div to another works. But transferring it back doesn't work.
This is my html:
<h4>Video Tags</h4>
<div id="tagbox-1">
<span class="tag-filter">tag 1</span>
<span class="tag-filter">tag 2</span>
<span class="tag-filter">tag 3</span>
</div>
<h4>Video Filters</h4>
<div id="tagfilter-1">
</div>
Then this is my javascript/jquery:
function tag_ui_move(tag_object,filter_move_to){
$(filter_move_to).append($(tag_object)).fadeIn();
$(tag_object).remove();
}
$(document).ready(function(){
var stored_tag = [];
$('[id^="tagbox-"] > span').each(function(){
$(this).click(function(){
tag_ui_move(this,'div[id^="tagfilter-"]');
});
});
$('div[id^="tagfilter-"] > span').each(function(){
$(this).click(function(){
tag_ui_move(this,'div[id^="tagbox-"]');
});
});
});
This is pretty much the gist of my html and code. I simplified it because there are more tagbox- and tagfilter- divs.

The problem is that $('[id^="tagbox-"] > span') selects all of the tag span elements that exist in the tagbox at that moment and then you bind a click handler to each of them that moves it to the filter div. And then $('div[id^="tagfilter-"] > span') selects all of the tag span elements that exist in the filter div at that moment and there aren't any. So there is no handler bound to move the elements back.
Also there is no need to use an .each() loop to individually bind .click() to each element in the loop: you can just call .click() directly and it will bind the handler to all elements that matched your selector.
The solution is to use a delegated handler, where you use .on() to bind the click to the parent div elements but supply a secondary selector that jQuery will automatically test at the time the click event occurs:
function tag_ui_move(tag_object,filter_move_to){
$(filter_move_to).append(tag_object).fadeIn();
//$(tag_object).remove(); <-- commented out: don't remove the element,
// because append *moves* it
}
$(document).ready(function(){
var stored_tag = [];
$('[id^="tagbox-"]').on('click', 'span.tag-filter', function(){
tag_ui_move(this,'div[id^="tagfilter-"]');
});
$('div[id^="tagfilter-"]').on('click', 'span', function(){
tag_ui_move(this,'div[id^="tagbox-"]');
});
});
That way, when a click on any element within '[id^="tagbox-"]' occurs, jQuery tests if the target element matches the selector 'span.tag-filter' and if and only if it does it calls your handler function. So then the clicks work on the elements even when they're dynamically moved back and forth between the two parent divs.
Demo: http://jsfiddle.net/6m4aac3k/

HTML
<h4>Video Tags</h4>
<div id="tagbox">
<span class="tag-filter">tag 1</span>
<span class="tag-filter">tag 2</span>
<span class="tag-filter">tag 3</span>
</div>
<h4>Video Filters</h4>
<div id="tagfilter">
</div>
Javascript
function tag_ui_move(tag_object,filter_move_to){
$(filter_move_to).append($(tag_object)).fadeIn();
}
$(document).ready(function(){
$(".tag-filter").click(function(){
var inTagBox=$(this).parent( "#tagbox" ).length>0;
var moveTo=inTagBox ? '#tagfilter' : '#tagbox';
tag_ui_move(this,moveTo);
});
});
JSFiddle
Tag filter

Related

Select all DOM elements not under a specific parent with jquery

here is a simple example of my html stucture
<div>
<p class="doNotWant">
HTML stucture is not set in stone
<a class="linkToSelect">do not want</a>
</p>
</div>
<p>
html structure and tags may vary, very simplified example
<a class="linkToSelect">want this one</a>
</p>
then I'm trying to select only the link not under the "doNotWant" parent class in my javascript...
$(document).on('click', '.linkToSelect', function (e) {
// this code selects both links
console.log('my logic');
}
I've tried using :not() but not had any success yet.
Using :not() change your selector to:
$(document).on('click', 'p:not(".doNotWant") .linkToSelect', function(e) {
$(document).on('click', 'p:not(".doNotWant") .linkToSelect', function(e) {
// this code selects both links
console.log('my logic');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p class="doNotWant">
HTML stucture is not set in stone
<a class="linkToSelect">do not want</a>
</p>
</div>
<p>
html structure and tags may vary, very simplified example
<a class="linkToSelect">want this one</a>
</p>
In Jquery you can use the :not() selector.
You can do the following if you don't know the parent element but know that its parent is a div.
$(document).on('click', 'div > :not(.doNotWant) > .linkToSelect', function (e) {
console.log('your logic');
});
Here is a fiddle

jQuery click event removing first element

Im working on a project and on my .ejs file I have a popup:
<div id="just-claimed-popup2" class="popup">
<h6>You just claimed:</h6>
<h2 id="card-just-claimed"></h2>
<p class="show-message">Show this Screen!</p>
<button id="deletePromoFromHome" class="close-button">Close</button>
</div>
On my javascript file I have a code that creates cards on a loop:
$('#promotion-container footer').before(`
<div class="promo card promo${i}">
<div class="promo-wrapper">
<div class="promo-header">
<h2 class="promo-title">${eventName}</h2>
<span class="close-promo-wrapper"><span class="close-promo"></span></span>
</div>
<div class="promo-info">
<span class="promo-details">
<p class="promo-detail promo-location">${eventLocation}</p>
<p class="promo-detail promo-date">${eventDate}</p>
<p class="promo-detail promo-time">${eventTime}
<span class="promo-description"></span>
<span class="buttonRedemp${i}">
<button class="redddButt load-button2" data="Reedem Card">Reedem Card</button>
</span>
</div>
</div>
</div>
`)
I want the card to disappear when people click 'redddButt', this is my code:
$(`#promotion-container .promo${i} .redddButt`).on('click', function(e){
e.stopPropagation();
$(`div.promo${i}`).addClass('toDelete')
var esc = $.Event("keyup", { keyCode: 27 });
$(document).trigger(esc);
$('#just-claimed-popup2').addClass('reveal');
$('#card-just-claimed').text(eventName);
$('#deletePromoFromHome').click(function(){
$('div.toDelete').fadeOut("slow")
})
})
PROBLEM: it always removes just the first card clicked and if you click the button in another one it stops working, so it only works once. If I console.log something the click event is happening, it's just not running the code inside of it.
Try changing your handler to:
$('body').on('click', `#promotion-container .promo${i} .redddButt`, function(e){
//function stuff here
}
The problem might be that elements are generated after the handler is attached.
Your code is missing some few closing tags. Since the cards are dynamically generated, try using (not tested):
var buttonContext;
$(document).on('click', '#promotion-container .promo .redddButt', function() {
buttonContext = $(this);
// Something
});
$('#deletePromoFromHome').click(function(){
buttonContext.closest('.promo').fadeOut("slow");
});
You can omit this line: $(div.promo${i}).addClass('toDelete');
The cards may have a single class (.promo) instead of (.promo#), unless may be you want to do further manipulation (say different styling etc).
Check this for more details on $(document): https://stackoverflow.com/a/32066793/3906884

JQuery - Detecting which div box was clicked

I'm trying to detect which div box was clicked with JQuery and I'm not sure what I am doing wrong. I'm aware that I can approach this in a different method by directly calling functions if a div box is clicked, but I wish to do it this way by first determining what was clicked.
$(document).ready(function() {
$(document).click(function(event){
var id = event.target.id; //looks for the id of what was clicked
if (id != "myDivBox"){
callAFunction();
} else {
callSomeOtherFunction();
}
});
});
Thank you for any suggestions!
You could use the closest function to get the first ancestor element with tag div, see following example:
$(document).ready(function() {
$(document).click(function(event){
var parentDiv = $(event.target).closest("div");
console.log(parentDiv.prop("id"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<span id="span1">Test1</span>
</div>
<div id="div2">
<span id="span2">Test2</span>
</div>
I hope it helps you. Bye.
No matter what you click, you will always know the element that was clicked:
$("#myDiv").click(function(e){
alert("I was pressed by " + e.target.id);
});
Knowing that you don't want to add this to every div, and you have your click on your document, you'll need to figure out what divs can be reported as "clicked".
In order to do this you'll either need a strict hierarchy of elements in your DOM (which is anoyingly bad) or you can decorate "clickable" div's with a specific class.
Fiddle - similar to below. https://jsfiddle.net/us6968Ld/
I would use closest in Jquery to get the result you want.
$(document).ready(function() {
$(document).click(function(event){
var id = event.target.id;
var clickDiv = $(event.target).closest('div[class="clickable"]');
alert(clickDiv[0].id);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="clickable" id="clickable1">
<span id="foo"> click me - Foo - clickable 1</span>
</div>
<div id="notClickable1">
<div class="clickable" id="clickable2">
<span id="span1">
Click Me Inside Span 1 - clickable 2
</span>
</div>
<div class="clickable" id="clickable3">
<div id="notClickable2">
<div id="notClickable3">
<span id="click me">Click Me - clickable 3</span>
</div>
</div>
</div>
</div>
try this:
$('div').click(function() {
alert($(this).attr('id'));
});
https://jsfiddle.net/1ct0kv55/1/

Working on DOM elements, finding next class

I have problem with working on DOM elements.
This is my HTML:
<div class="movie__feature">
▲
</div>
<div class="movie__images">
<span class="similarity_points">9</span>
<a href="http://www.filmypodobnedo.pl/Top-Gun/" title="Filmy podobne do Top Gun">
<img alt="Filmy podobne do Top Gun" src="http://www.filmypodobnedo.pl/photos/Top-Gun.jpg"/>
</a>
</div>
<div class="movie__feature">
▼
</div>
</div>
When I click on .plus class, I need to go to .similarity.
This is my jQuery:
$('.plus').click(function(e){
e.preventDefault();
var self = $(this);
self.closest('div').find('.similarity_points').text('10');
}
How my num should look?
The closest div doesn't contain .similarity_points as a descendent. You could use this:
self.closest('div').parent().find('.similarity_points').text('10');
But, be aware that code which is highly dependant on the structure of the DOM is also fragile.
In your code you are going up to .movie__feature, and then you are looking for children with the .similarity_points class.
You need to go up one more level and then look for the child element:
$('.plus').click(function () {
$(this).closest('div').parent().find('.similarity_points').text('10');
return false;
});

target mutiple classes above (this) in jQuery?

I've built a simple dropdown menu to replace some html select menus like so:
$('html, .currentPage').click(function() {
$('.currentMenu').slideUp('fast');
});
$('.currentPage').click(function(e){
if(!$(this).next().is(":visible")) {
$(this).next().stop().slideDown('fast');
}
e.stopPropagation();
});
$(".currentMenu li").click(function(e){
e.preventDefault();
$(".currentPage").html($(this).text());
});
However, if I were to have more than one menu, the final part:
$(".currentMenu li").click(function(e){
e.preventDefault();
$(".currentPage").html($(this).text());
});
will occur on both menus. How can I target the ".currentPage" class for that specific menu only?
HTML:
<div class="menuWrap font">
<div class="currentPage">Trebuchet MS</div>
<div class="currentMenu">
<ul>
<li>Arial</li>
<li>Helvetica</li>
<li>Droid Sans</li>
<li>Trebuchet MS</li>
<li>Georgia</li>
<li>Droid Serif</li>
</ul>
</div>
</div>
<div class="menuWrap fontSize">
<div class="currentPage">12pt</div>
<div class="currentMenu">
<ul>
<li>9pt</li>
<li>10pt</li>
<li>11pt</li>
<li>12pt</li>
<li>13pt</li>
</ul>
</div>
</div>
You have two options. The first is to traverse the DOM to find the nearest .currentPage element from .currentMenu li. Given your HTML structure, this should work:
$(".currentMenu li").click(function(e){
e.preventDefault();
$(this).closest(".currentMenu").prev().html($(this).text());
});
The second option is to put this code into a plugin which you apply to an element, so you always know the context in which to select elements in.
OK, based on your updated question. .currentMenu and .currentPage are siblings. So you can navigate to the parent element, then drill down to the currentPage. Here's a fiddle: http://jsfiddle.net/DuPuJ/

Categories

Resources