remove onclick when attached to children - javascript

I have the following code:
layoutOverlaysBldg = $("#layout-overlays-bldg")
layoutOverlaysBldg.on("click", "div", function(event) {
var floor;
console.log("floornum: " + this.dataset.floornum);
floor = parseInt(this.dataset.floornum);
...
$("#choose-floor").fadeOut();
$("#choose-apt").fadeIn();
});
later - based on data I'm getting back from the DB - I want to remove some of the .on("click", "div", ...) from only some of the divs. I already have the selector that is getting the right divs but I cannot figure out how to remove the click event. I have tried .off("click") after selecting the right div but it has no effect.

This issue here is because you are using a delegated event. You can add or remove the event for all child elements, but not individual ones given your div selector.
With that in mind the easiest way to do what you need is to add the event based on a class, then add and remove that class on the children as needed. Something like this:
layoutOverlaysBldg = $("#layout-overlays-bldg")
layoutOverlaysBldg.on("click", "div.clickable", function(event) {
// your code...
});
You can then enable/disable the event on the child div by adding or removing the .clickable class.

You can try like this :
Example :
<div id="test">
<div id="first">first</div>
<div id="second">second</div>
</div>
<div onclick="unbindSecondDiv();">UNBIND</div>
<script>
function unbindSecondDiv()
{
test = $("#second")
test.unbind("click");
alert('Selected Area Click is Unbind');
}
$(document).ready(function(){
//BIND SELECTED DIV CLICK EVENT
test = $("#test > div")
test.bind("click" , function(event) {
alert($(this).attr('id'));
});
});
</script>
In the above example , selected DIV elements click event is bind.
And after execute function unbindSecondDiv() , second DIV click event will be unbind.
Have a try , may helps you.

Related

Div Increment on button click

Need javascript for incrementation...
I have two with class names, parent and child (child inside the parent).
Each has a button outside them. If I click the button outside the parent, the div should be incremented with child inside it.
And if the button outside the child is clicked, the child div must be incremented.
Find the below link as demo.
LINK
HTML code is
<div class="parent">
<div class="child">
</div><br>
Add one more child
</div><br>
Add one more Parent
You can use a click handlers with event delegation and cloning like below
jQuery(function($){
var _parent = $('.parent').eq(0).clone();
$(document).on('click', '.inc-child', function(){
var $p = $(this).parent();
$p.find('.child').first().clone().insertBefore(this)
})
$('.inc-parent').on('click', function(){
_parent.clone().insertBefore(this)
})
})
Demo: Fiddle
Check this JS
$(document).ready(function() {
$("button[name='addDom']").click(function() {
var domElement = $('<div class="module_holder"><div class="module_item"><img src="images/i-5.png" alt="Sweep Stakes" /></div></div>');
$(this).after(domElement);
});
});

Catch the onClick event on `span` tags

I have got a lot of span tags inside my div elements. Each div has a unique id.I want to add an onclick event to the span elements in each div uniquley. How can i do that?
<div class="bootstrap-tagsinput"id="1">
<span class="tag label label-info">Access control lists</span>
<span class="tag label label-info">Network firewall</span>
</div>
<div class="bootstrap-tagsinput"id="2">
<span class="tag label label-info">Access control lists</span>
<span class="tag label label-info">Network firewall</span>
</div>
My current script which catches all the span elements irrespective of the div.
$('span.label-info').click(function() {
var news=$('input[type=text][id="vuln<?php echo $model->v_id;?>"]').val()+','+$(this).text();
$('input[type=text][id="vuln<?php echo $model->v_id;?>"]').val(news);
return false;
});
How can i catch click on span elements inside each div separately?
I think you're looking at it the wrong way. Instead of having a separate click handler for each div, you can keep the shared click handler, but find out which div is the parent, and use its ID in the subsequent selectors.
$('span.label-info').click(function() {
// find the parent/ansector that is a div and has the class
var divId = $(this).closest('div.bootstrap-tagsinput').prop('id');
var news=$('input[type=text][id="vuln' + divId + '"]').val()+','+$(this).text();
$('input[type=text][id="vuln' + divId + '"]').val(news);
return false;
});
Your code should work to add a click even handler to each span.
$('span.label-info').click(function() {
$(this).attr('id'); //<--$(this) is a handle to the clicked span
$(this).parent().attr('id'); //<-- $(this).parent() references the parent div
});
It's worth mentioning, consider changing .click() to .on('click').
Also - if you wanted to bind once without rebinding after spans were dynamically added to the div, you could bind it like this:
$('div').on('click', 'span.label-info').click(function() {
/* <-- do stuff with $(this) or $(this).parent() here --> */
});
http://jsfiddle.net/GZVdL/3/
Hi.
in your span click event you can find parent div and then get its attribute id to find which div it is.
Below is the code
$(document).ready(function(){
$(".tag").click(function(){
alert($(this).parent().attr("id"));
});
});

$(*).click event click it and all of its parent.

This is my code:
<p>
<div>
<div><span>Hello</span></div>
<span>Hello Again</span>
</div>
<div>
<span>And Hello Again</span>
</div>
</p>
<b>Click Hellos to toggle their parents.</b>
<script>
function showParents() {
$("div").css("border-color", "white");
var len = $("span.selected")
.parents("div")
.css("border", "2px red solid")
.length;
$("b").text("Unique div parents: " + len);
}
$("*").click(function () {
$("b").text($(this).parents().length);
});
</script>
The problem is when I click on a span, this shows 0 instead of 3!
I think the problem is *
Now the question is, how do I get the parent count when I don't know the type of the element?
The problem is event propagation(bubbling). The click event gets propagated to the root of the document from the clicked element triggering each of the click handler associated with those ancestor elements, so when the html element's click handler is triggered there is no more parents so you gets 0 as the result.
Demo: Fiddle - take a look at the console
Instead you can bind the click handler only to the document object then use the event's target property to find the element which triggered the click and find its parents
$(document).click(function (e) {
$("b").text($(e.target).parents().length);
});
Demo: Fiddle

JS Events not attaching to elements created after load

Problem: Creating an Element on a button click then attaching a click event to the new element.
I've had this issue several times and I always seem to find a work around but never get to the root of the issue. Take a look a the code:
HTML:
<select>
<option>567</option>
<option>789</option>
</select>
<input id="Add" value="Add" type="button"> <input id="remove" value="Remove" type="button">
<div id="container">
<span class="item">123</span>
<br/>
<span class="item">456</span>
<br/>
</div>
JavaScript
$(".item").click(function () {
if ($("#container span").hasClass("selected")) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
$("add").click(function() {
//Finds Selected option from the Select
var newSpan = document.createElement("SPAN");
newSpan.innerHTML = choice;//Value from Option
newSpan.className = "item";
var divList = $("#container");
divList.appendChild(newSpan);//I've tried using Jquery's Add method with no success
//Deletes the selected option from the select
})
Here are some methods I've already tried:
Standard jQuery click on elements with class "item"
Including using the `live()` and `on()` methods
Setting inline `onclick` event after element creation
jQuery change event on the `#Container` that uses Bind method to bind click event handler
Caveat: I can not create another select list because we are using MVC and have had issues retrieving multiple values from a list box. So there are hidden elements that are generated that MVC is actually tied to.
Use $.on instead of your standard $.click in this case:
$("#container").on("click", ".item", function(){
if ( $("#container span").hasClass("selected") ) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
It looks to me like you want to move the .selected class around between .item elements. If this is the case, I would suggest doing this instead:
$("#container").on("click", ".item", function(){
$(this)
.addClass("selected")
.siblings()
.removeClass("selected");
});
Also note your $("add") should be $("#add") if you wish to bind to the element with the "add" ID. This section could also be re-written:
$("#add").click(function() {
$("<span>", { html: $("select").val() })
.addClass("item")
.appendTo("#container");
});

javascript set element background color

i have a little javascript function that does something when one clicks on the element having onclick that function.
my problem is:
i want that, into this function, to set a font color fot the html element having this function onclick. but i don't suceed. my code:
<script type="text/javascript">
function selecteazaElement(id,stock){
document.addtobasket.idOfSelectedItem.value=id;
var number23=document.addtobasket.number;
number23.options.length=0;
if (stock>=6) stock=6;
for (i=1;i<=stock;i++){
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
}
</script>
and how i use it:
<li id = "product_types">
<a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?></a>
</li>
any suggestions? thanks!
i have added another function (jquery one) that does partially what i need. the new problem is: i want that background color to be set only on the last clicked item, not on all items that i click. code above:
$(document).ready(function() {
$('.product_types > li').click(function() {
$(this)
.css('background-color','#EE178C')
.siblings()
.css('background-color','#ffffff');
});
});
any ideas why?
thanks!
I would suggest
$(document).ready(function() {
$('.product_types > li').click(function() {
$('.product_types > li').css('background-color','#FFFFFF');
$(this).css('background-color','#EE178C');
});
});
Your element could have this code:
<li id = "product_types" onclick="selecteazaElement(this);" <...> </li>
To change the foreground color of that element:
function selecteazaElement(element)
{
element.style.foregroundColor="#SOMECOLOR";
}
If you want to change the background color on only the last element clicked, each element must have a different id. I'd suggest naming each one something like product_types1, product_types2, ..., product_typesN, and so on. Then have a reset function:
function Reset()
{
for (var i = 1; i <= N; i = i + 1)
{
document.getElementById('product_types'+i).style.backgroundColor="#RESETCOLOR";
}
}
When you call your selecteazaElement(this) function, first call the Reset function, then set the new element:
function selecteazaElement(element)
{
Reset();
element.style.backgroundColor="#SOMECOLOR";
}
This way all of the elements that start with product_types followed by a number will be reset to one particular color, and only the element clicked on will have the background changed.
The 'scope' of the function when invoked is the element clicked, so you should be able to just do:
function selecteazaElement(id,stock){
document.addtobasket.idOfSelectedItem.value=id;
var number23 = document.addtobasket.number;
number23.options.length=0;
if (stock>=6){
stock=6;
}
for (var i=1;i<=stock;i++){
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
// Alter 'this', which is the clicked element in this case
this.style.backgroundColor = '#000';
}
$(function() {
/*if product_types is a class of element ul the code below
will work otherwise use $('li.product_types') if it's a
class of li elements */
$('.product_types li').click(function() {
//remove this class that causes background change from any other sibling
$('.altBackground').removeClass('altBackground');
//add this class to the clicked element to change background, color etc...
$(this).addClass('altBackground');
});
});
Have your css something like this:
<style type='text/css'>
.altBackground {
background-color:#EE178C;
/* color: your color ;
foo: bar */
}
</style>
Attach a jQuery click event to '#product_types a' that removes a class from the parent of all elements that match that selector; then, add the class that contains the styles you want back to the parent of the element that was just clicked. It's a little heavy handed and can be made more efficient but it works.
I've made an example in jsFiddle: http://jsfiddle.net/jszpila/f6FDF/
try this instead:
//ON PAGE LOAD
$(document).ready(function() {
//SELECT ALL OF THE LIST ITEMS
$('.product_types > li').each(function () {
//FOR EACH OF THE LIST ITEMS BIND A CLICK EVENT
$(this).click(function() {
//GRAB THE CURRENT LIST ITEM, CHANGE IT BG, RESET THE REST
$(this)
.css('background-color','#EE178C')
.siblings()
.css('background-color','transparent');
});
});
});
If I am correct, the problem is that the click event is being binded to all of the list items (li). when one list item is clicked the event is fired on all of the list items.
I added a simple .each() to your code. It will loop through each of the list items and bind a event to each separately.
Cheers,
-Robert Hurst

Categories

Resources