I want an element to be removed from the list by clicking on it in the selectize-dropdown-content
So that the elements do not disappear after adding from the list, I used hideSelected: false,
The click event doesn't work on this elements, I can't catch it
The problem is that after my code works and the element is removed, onItemAdd immediately works and it is added to the list again)
I have this code:
$(document).on('mousedown',function (e){
if ($(e.target).hasClass('option') && $(e.target).hasClass('selected')){
var value = $(e.target).attr("data-value");
var control = $(e.target).parents('.selectize-control').siblings('.selectized')[0].selectize;
control.removeItem(value);
control.refreshItems();
control.refreshOptions();
}
});
i tried to catch click events or something but they don't apply to these elements
Related
Okay, I have a todo app that i'm creating with JS. I have an addtodo function which adds the items when clicked and also runs a for loop for each of these list elements, which have a classname of 'list', to style them. The thing is, the for loop runs everytime I add the todo list which I think add's multiple event listeners to the already existing items with the same function. I'm trying to toggle a class for priority function when clicking on a paragraph with classname of 'thevalue'. My problem is the event listener runs multiple times and cancels the toggle. The first item runs once, which is correct, and the second item runs, twice, and the third runs three times as follow. I will attach the code below. It would be of great help if you could solve my issue.
var theListPara = document.getElementsByClassName('thevalue');
if (theListPara[0]) {
for (var i = 0; i < theListPara.length; i++) {
theListPara[i].addEventListener("click", changePriority);
}
function changePriority() {
var theClassName = this.parentElement.classList.contains('normal');
if (theClassName) {
this.parentElement.classList.toggle('high');
}
}
}
This whole line of code runs whenever the add todo is clicked.
Event Delegation is the way forward. Its philosophy is very simple, event listener is attached to static-parent-element then it analyses the bubbled event.target. if match is found then the desired operation can be performed.
document.querySelector('.static-parent-element').addEventListener("click", function(e) {
if(e.target && e.target.classList.contains('thevalue')) {
// thevalue item found
if (this.parentElement.classList.contains('normal')) {
this.parentElement.classList.toggle('high');
}
}
});
Element.matches() API can also used to validate element matches a given selector.
The Element.matches() method returns true if the element would be selected by the specified selector string; otherwise, returns false.
if(e.target.matches('.thevalue')){
}
I hit a problem with the onclick function when i add divs with ids like "n_block"+(1-~). When I use the jquery zoom function on the objects to make them smaller or bigger onClick doesn't work anymore. I'm not really good at programming so the code might be kind of confusing.
Heres the code i use for the onClick of items:
$(document).on("click",function (e, ui){
//When the document gets clicked, check if one of the items was clicked.
if($(e.target).is($("#n_block" + cloneCount1)) || $(e.target).is($("#n_block" + cloneCount1+ " span"))){
//Set current item.
var item = $("#n_block" + cloneCount1);
//Set style to current item.
item.css("border-color", "Black");
item.css("border-width","2px");
item.css("background-color", "floralwhite");
jsPlumb.repaintEverything();
//Check if key Delete was pressed while item selected & delete that item with his children.
$('html').keydown(function(e){
if(item.css("border-width")=="2px"){
if(e.keyCode == 46) {
/* Prevents line bugging*/
jsPlumb.detachEveryConnection();
jsPlumb.deleteEveryEndpoint();
var razred = getClass(item, "b_"),
id = item.prop("id");
item.remove();
if(razred == "b_2"){
$(".ovoj."+id).remove();
}
else if (razred == "b_4"){
$(".ovojLoop."+id).remove();
$(".empty_block_c."+id).remove();
}
if ( $('.objects').find('div').length == 2) {
$(".objects").empty();
$(".objects").append('<div class="b_s" id="start_block">START</div><p id="start_text">Insert symbols here!</p><div class="b_s" id="end_block">STOP</div> ');
}else{
/* Connects objects together with line. ****/
povezi(cloneCount, tip_crte, ".objects");
}
}
jsPlumb.repaintEverything();
}
});
}
// If item is not clicked set this css to the current item.
else{
$("#n_block" + cloneCount1).css("border-width","1px");
jsPlumb.repaintEverything();
}
});
And heres the zoom code for zooming in when button is clicked:
var currentZoom = 1.0;
$(".zoomin").click(function (){
//Detaches the connections from item to item.
jsPlumb.detachEveryConnection();
jsPlumb.deleteEveryEndpoint();
//Prevents spamming of button, animates the objects
$(".project").stop().animate({ "zoom": currentZoom += .1}, "slow", function() {
if(!$(".objects").children().is($("p"))){
povezi(cloneCount, tip_crte, ".objects");
}
});
});
Use event delegation for binding events to dynamically added elements.
$(document).on('click', ".zoomin", function (){
//Your code.
});
When you use normal .click() to bind event to an element, then that even gets bound to only those elements which exist in the DOM at the moment of the execution of code. Using event delegation, you can tell jQuery that we need to add the handler to every '.zoomin' element which comes inside a particular element no matter when it is added.
The solution depends when exactly is the script which tries to bind the events are executed.
For Eg: Lets assume this script is in document ready function of jquery
$(document).ready(function(){
$(".zoomin").click(function (){
//your logic here
});
});
Here this script is executed when the page HTML is completed loading into the browser. Now when the script executes it tries to find a element with the class zoomin and if found it will add a event to that element and move on. If the element is not found the script just moves on. So we should actually take care of when the script is executed and is the intended element available at that particular instant of time. If the element is not yet available in the HTML (element might come in later dynamically using jquery) we have 2 options to bind event to the element.
1) Execute the script when the element is being added into the HTML: Lets say I have a event which brings up a pop up with some image. Now I want to zoomin and zoomout the image. Since the image in the popup is added dynamically and I have control of when its being added, I can do this.
$(document).ready(function(){
$('.ViewImage').on('click',function(){
// some code is executed which brings up the popup
// now we know that the image is added into html we can now run the script
$(".zoomin").click(function (){
//your logic here
});
});
});
2) We have no Clue/ Control when the element is added into HTML but still want to bind a event to it: This is scenario where we have no control on when the element is being added or not sure where it is being added from (might be from some external plugin used etc) or not having control at all on the element which is added. Thats when we use this syntax as suggested by #Rejith R Krishnan
$(document).on('click', ".zoomin", function (){
//Your code.
});
This will work on all the elements which are in the HTML at the time of execution of the script and on the elements which will be added in the future with the class name zoomin. So this script can be placed inside/ outside of jquery document ready event
I have created a series of elements that when you click on any one of them, they will expand, pushing the other elements out of the way. Initially if you clicked on it again the element would contract, but now I want to take the close functionality and put it in a button with in the element.
Initially when you click on the element, I use jQuery to add a number of classes to a variety of elements.
$(".left > .elem").click(function () {
$(this).addClass("expand");
$(this).parent().addClass("WithLarge");
$(this).children(".bar").addClass("visible");
$(this).children(".reduce_button").addClass("visible");
$(".right").addClass("shift_right");
});
When I click the close button I would like to remove those classes.
$(".reduce_button").click(function () {
$(this).parent().removeClass('expand');
$(this).parent().removeClass("WithLarge");
$(this).parent().children(".bar").removeClass("visible");
$(this).parent().children(".reduce_button").removeClass("visible");
}
The problem is, those classes aren't budging.
You can try it out on the JSFiddle
Click on the yellow box(".left > .elem"), it expands pushing the others out of the way, click on the red box(".reduce_button"), and nothing happens. I tried
console.log($(this).parent().hasClass('expand'));
$(this).parent().removeClass('expand');
console.log($(this).parent().hasClass('expand'));
to see if it has been removed. It returns false, even though the class is still there.
Why can't I remove these classes?
You ARE removing the class. But, the click on the .reduce_button is also triggering the .elem click event, which adds the class back again.
EDIT:
As commented below by j08691, you can add stopPropagation to keep the event of going on to the next listener, like:
$(".reduce_button").click(function (e) {
$(this).parent().removeClass('expand');
e.stopPropagation();
...
Here is your fiddle updated: http://jsfiddle.net/HybHK/9/
The "show" event doesn't appear to be working on a collapsible that is dynamically created. Multiple panels stay open when calling the javascript function. Clicking the panel headers still works fine, and if I manually click the panels first, then the "show" method appears to work. But ONLY if I click on the panel headers first. Any ideas?
JSFiddle example: http://jsfiddle.net/victoryismine06/N6rey/
//Click handler
$( "#btnOpen" ).click(function() {
var idx = $("#idx").val();
$("#accordion2 #collapse" + idx).collapse('show');
});
Try this way.
$("#btnOpen").click(function () {
var idx = $("#idx").val();
//Just find the data-toggle element respective to the current element and invoke the click on it.
$("#collapse" + idx).filter(':not(.in)').prev().find('[data-toggle]').trigger('click.bs.collapse.data-api');
//or just simply do:
// $("#accordion2").find('[data-toggle]:eq(' + idx + ')').trigger('click.bs.collapse.data-api');
//Or you can also do:
//$("#accordion2 .panel-collapse.in").not($("#collapse" + idx).collapse('show')).collapse('hide');
});
Demo
Reason being invocation of collapse method will just collapse current elements based on what type is passed, i.e hide, show or toggle. it doesnot handle the auto collapse of other open items which is handled in the custom click event attached to [data-toggle] elements in the collapsible. I.e in the below section:
$(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) {
So invoking a click event on the respective data-toggle element will handle the real collapse scenario.
Basicllay i have a div with a class called .li-level-1, and inside that i have differnt ul's with lists. i Have it set up so when you click on a li-level-1 div displays the ul's and li's inside that div by animating a drop down and when you click on the next one it closes the one previously opened and slidesDown the next one.
the only thing is the a links that are inside the div's seem to trigger the slideUp/Down on level-1 and animation as well.
any Suggestions?
$('.sitemap_page .li-level-1').each(function(){
$(this).find('ul.ul-level-2').hide();
$(this).click(function(){
var this_list = $(this);
this_list.parent().find('.open').each(function(){
$(this).slideUp(function(){
this_list.find('ul.ul-level-2').addClass("open").slideDown();
}).removeClass('open');
});
if(this_list.find('ul.ul-level-2.open').length == 0) {
this_list.find('ul.ul-level-2').addClass("open").slideDown();
}
});
});
That's because of event bubbling: the click event raised on the <a> elements bubble up to their containing <div> and cause your event handler to execute.
One way to work around that problem would be to use event.target to determine the event's origin, and only perform the sliding animations if the event did not originate on a link:
$(this).click(function(event) {
if (!$(event.target).is("a")) {
var this_list = $(this);
this_list.parent().find('.open').each(function() {
$(this).slideUp(function() {
this_list.find('ul.ul-level-2').addClass("open").slideDown();
}).removeClass('open');
});
if (this_list.find('ul.ul-level-2.open').length == 0) {
this_list.find('ul.ul-level-2').addClass("open").slideDown();
}
}
});
The problem is with event bubbling as sugested by Frederic. The other possible solution is to divide your div into title and content divs. Hold data in content and check click on title (not on the parent list). This means rebuilding the handler but the code will be clearer and it won't depend on event.target.