I am trying to get the tag name of the element clicked inside an li when the user clicks on the element. The li element is added dynamically to the HTML code. To do this I am using the code below however it does not seem to be working.
$('li *','div#contentWrapper').on('click','#interfaceContainer #left #sortableTestComponents li',function(e){
e.stopPropagation();
var domEl = $(this).get(0);
alert(domEl.tagName);
if(!$(event.target).hasClass("deleteTestComp")){
var type = $(this).find('div.headerName').html();
var information = $(this).find('input[type=hidden]').val();
if(type == "CliSessionType"){
parseCliComponent(information);
}
else if(type == "DBSessionType"){
parseDbComponent(information);
}
else{
parseScreenComponent(information);
}
}
});
Why is my code not working? Nothing happens when the user clicks on an element.
JSFiddle - http://jsfiddle.net/3FxQE/
Since you are interested in click events in li elements which comes under #interfaceContainer, the event registration must be $('#interfaceContainer').on('click','li',function(e){...});
Then to get the tagName, you need to use the actual source of the event this is available in e.target so you need to use $(e.target).get(0) to get the clicked dom element.
$('#interfaceContainer').on('click','li',function(e){
e.stopPropagation();
var domEl = $(e.target).get(0);
alert(domEl.tagName);
if(!$(event.target).hasClass("deleteTestComp")){
var type = $(this).find('div.headerName').html();
var information = $(this).find('input[type=hidden]').val();
if(type == "CliSessionType"){
parseCliComponent(information);
}
else if(type == "DBSessionType"){
parseDbComponent(information);
}
else{
parseScreenComponent(information);
}
}
});
Demo: Fiddle
You are trying to use a context where you don't need to, in your selector. Change $('li *','div#contentWrapper') with $('div#contentWrapper') and $(event.target) with $(e.target). A working fiddle is here
$('div#contentWrapper').on('click', '#interfaceContainer #left #sortableTestComponents li', function (e) {
e.stopPropagation();
var $this = $(this),
domEl = $this.get(0);
alert(domEl.tagName);
if (!$(e.target).hasClass("deleteTestComp")) {
var type = $this.find('div.headerName').html(),
information = $this.find('input[type=hidden]').val();
if (type == "CliSessionType") {
parseCliComponent(information);
} else if (type == "DBSessionType") {
parseDbComponent(information);
} else {
parseScreenComponent(information);
}
}
});
Related
I have several of these lines in my HTML:
<img src="Iconos/heart.png" alt="Fave" class="fave_icon">
I want to change the 'src' when one of them is clicked (but ONLY on that one)
I tried this but it does not work:
$(document).on('click', '.fave_icon', function (event) {
if ($(this).getAttribute('src') == "Iconos/heart.png")
{
$(this).src = "Iconos/heart_coloured.png";
}
else
{
$(this).src = "Iconos/heart.png";
}
});
this is the function you're in.
The clicked element is event.target. Replace $(this) with $(event.target) and it will work.
For the general case, where the targeted element has children, it's possible that the target of your click is a child (of .fave_icon). Use closest() to target the closest .fave-icon:
$(document).on('click', '.fave_icon', function(event) {
let elem = $(event.target).closest('.fave_icon');
if (elem.getAttribute('src') == "Iconos/heart.png") {
elem.src = "Iconos/heart_coloured.png";
} else {
elem.src = "Iconos/heart.png";
}
});
I ended up solving it like this:
<img src="Iconos/heart.png" onclick="fav(this);" alt="Fave" class="fave_icon">
And then
function fav(heart){
if (heart.getAttribute('src') == "Iconos/heart.png")
{
heart.src = "Iconos/heart_coloured.png";
}
else
{
heart.src = "Iconos/heart.png";
}
Working on jquery clone with my current code everthing works fine.
first scenario if user select other from the drop down the text
field gets enabled
Second scenario if user click addmore button div gets clone
perfectly with id when user select other both Original and clone
textfield gets enabled actually it should be only the cloned should
get enabled not the enabled
Here is the current Jquery code
var i=1;
$(document).on("click", ".edu_add_button", function () {
var i=$('.cloned-row1').length;
$(".cloned-row1:last").clone(true).insertAfter(".cloned-row1:last").attr({
'id': function(_, id) { return id + i },
'name': function(_, name) { return name + i }
}).end().find('[id]').val('').attr({ 'id': function(_, id) { return id + i }
});
$(".cloned-row1:last").find(".school_Name").attr('disabled', true).val('');
if(i < $('.cloned-row1').length){
$(this).closest(".edu_add_button").removeClass('btn_more edu_add_button').addClass('btn_less btn_less1');
}
i++;
return false;
});
$(document).on('click', ".btn_less1", function (){
var len = $('.cloned-row1').length;
if(len>1){
$(this).closest(".cloned-row1").remove();
}
});
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(".school_Name").prop('disabled', false);
$(".school_Name").val('');
}else{
$(".school_Name").prop('disabled', true);
}
});
$(document).on('change', '.txt_degreName', function (){
var cur = $('.txt_degreName').index($(this));
$('.degree_Description').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$("#degree_Description").prop('disabled', false);
$("#degree_Description").val('');
}else{
$("#degree_Description").prop('disabled', true);
}
});
Here is the fiddle link
Kindly suggest me
thanks & regards
Mahadevan
DEMO
The issue comes be cause you are using class selector directly. You need apply value only to the text box which belongs in the same container. Use closest() to find the parent.
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
var container = $(this).closest('.container-fluid');
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(".school_Name", container).prop('disabled', false);
$(".school_Name", container).val('');
}else{
$(".school_Name", container).prop('disabled', true);
}
});
DEMO HERE
You need to refer proper element that has to be disabled and enabled.
Take the sibling of select's parent and find the input element to be disabled as below:
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$(this).closest('.col-xs-6').next('.col-xs-6').find('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', false);
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").val('');
}else{
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', true);
}
});
From what you did, you actually change every fields with class .school_Name, to achieve what you want you can add $(this).parents(".row").find(".class_name") so it only change the current div.
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(this).parents(".row").find(".school_Name").prop('disabled', false);
$(this).parents(".row").find(".school_Name").val('');
}else{
$(this).parents(".row").find(".school_Name").prop('disabled', true);
}
});
DEMO HERE
You can do it this way with targeting specific item using parent() and next() selector and also i prefer to access specific field instead of index(such as eq) for input.
var schoolObj = $(this).parent().next().find(".school_Name");
schoolObj.val($(this).val());
if ($(this).val() == "other") {
schoolObj.prop('disabled', false);
schoolObj.val('');
} else {
schoolObj.prop('disabled', true);
}
Here is the Fiddle
You can have a look for jquery traversing:
parent: https://api.jquery.com/parent/
Next: https://api.jquery.com/next/
Find: https://api.jquery.com/find/
and for full traversing: https://api.jquery.com/category/traversing/
I want to create an event when the content of a div changes, the event is called..
change = function(oldval,newval){
if (oldval != newval){
return true;
}
return false;
}
I want this function to be called everytime the content of a div changes ..Any idea how i can achieve this ?
I want this function to be called everytime the content of an element changes
If the content of an element equals to the value of form inputs:
One line code:
$(':input', $('#divId')).change(function(){alert('changed');});
Or the delegate option for dynamic added elements (still one line... (; ):
$('#divId').on('change', ':input', function(){ alert('changed');});
docs:
on
:input selector
If you arent planning on supporting IE you can use DOMNodeInserted and DOMNodeRemoved to check if elements are added or removed from your div.
$('#yourDiv').bind('DOMNodeInserted DOMNodeRemoved', function(event, oldvalue, newvalue) {
if (oldval != newval){
return true;
}
return false;
});
for IE support you can use
$(function() {
var $div = $("#yourDiv");
var content = $div.html();
var look = setInterval(function() {
var newcontent = $div.html();
if (html != newcontent ) {
change(content, newcontent);
content = newcontent;
}
},100);
function change(oldval, newval() {
if (oldval != newval){
return true;
}
return false;
}
});
I've got a form that uses jqTransform to replace the standard select boxes and radio buttons. It all works fine and dandy, except one thing that annoys me:
Since it replaces the select box with a list of links, when you type a letter to scroll it doesn't do anything. For instance, you click to open up the select, then type an S. It should scroll to the first S in the list, but nothing happens. Is there a way to re-instate this functionality? Below is the jqTransform code for the select box. I don't see a handler for this type of thing:
/***************************
Select
***************************/
$.fn.jqTransSelect = function(){
return this.each(function(index){
var $select = $(this);
if($select.hasClass('jqTransformHidden')) {return;}
if($select.attr('multiple')) {return;}
var oLabel = jqTransformGetLabel($select);
/* First thing we do is Wrap it */
var $wrapper = $select
.addClass('jqTransformHidden')
.wrap('<div class="jqTransformSelectWrapper"></div>')
.parent()
.css({zIndex: 10-index})
;
/* Now add the html for the select */
$wrapper.prepend('<div><span></span></div><ul></ul>');
var $ul = $('ul', $wrapper).css('width',$select.width()).hide();
/* Now we add the options */
$('option', this).each(function(i){
var oLi = $('<li>'+ $(this).html() +'</li>');
$ul.append(oLi);
});
/* Add click handler to the a */
$ul.find('a').click(function(){
$('a.selected', $wrapper).removeClass('selected');
$(this).addClass('selected');
/* Fire the onchange event */
if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
$select[0].selectedIndex = $(this).attr('index');
$('span:eq(0)', $wrapper).html($(this).html());
$ul.hide();
return false;
});
/* Set the default */
$('a:eq('+ this.selectedIndex +')', $ul).click();
$('span:first', $wrapper).click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
oLabel && oLabel.click(function(){$("a.jqTransformSelectOpen",$wrapper).trigger('click');});
this.oLabel = oLabel;
/* Apply the click handler to the Open */
var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper)
.click(function(){
//Check if box is already open to still allow toggle, but close all other selects
if( $ul.css('display') == 'none' ) {jqTransformHideSelect();}
if($select.attr('disabled')){return false;}
$ul.slideToggle('fast', function(){
var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
$ul.animate({scrollTop: offSet});
});
return false;
})
;
// Set the new width
var iSelectWidth = $select.outerWidth();
var oSpan = $('span:first',$wrapper);
var newWidth = (iSelectWidth > oSpan.innerWidth())?iSelectWidth+oLinkOpen.outerWidth():$wrapper.width();
$wrapper.css('width',newWidth);
$ul.css('width',newWidth-2);
oSpan.css({width:iSelectWidth});
$ul.css({height:'420px','overflow':'hidden'});
// Calculate the height if necessary, less elements that the default height
//show the ul to calculate the block, if ul is not displayed li height value is 0
$ul.css({display:'block',visibility:'hidden'});
var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff
(iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff
$ul.css({display:'none',visibility:'visible'});
});
};
Here is what we tried to do to implement this:
var oLinkOpen = $('a.jqTransformSelectOpen', $wrapper)
.keypress(function (e) {
$.each(myArray, function (i, l) {
var sc = l.substr(0, 1).toLowerCase();
var kc = String.fromCharCode(e.which);
if (sc == kc) {
$select[0].selectedIndex = i;
$('span:eq(0)', $wrapper).html(l);
$ul.hide();
return false;
}
});
});
Oh dang. I was missing the big picture without the code. Now I see what's going on... yeah, there's no "reinstating" the functionality since the new list of links is not actually a select box anymore. If jqTransform doesn't include a scrollable option by default I think you'll have to implement one.
If you look at their demo page, their "plain" select box works as expected (although it's hard to notice since all options start with "O", it WILL jump to the first "Option") and their styled select box does not.
Without looking deeper at the code, I suspect that means that a keypress capture is not implemented in the plug-in itself.
I'm afraid this isn't the "answer" you were probably hoping for. With any luck someone who has done this sort of thing before will hear your plea. ;-)
solution for jqTransform select keypress work link visit http://www.techapparatus.com/jqtransform-select-problem-with-keyboard-type-solution
Add the following code at the end of return this.each(function(index){ ... }); that is inside of $.fn.jqTransSelect function.
Also you have to install the scrollTo jquery plugin.
CODE:
var newChar;
$(document).bind("keydown", function (e) {
var char = String.fromCharCode(e.which);
var code = e.keyCode || e.which;
var charFound;
if( $ul.css('display') != 'none' ){
if (newChar != char){
newChar = char;
$ul.find('a').each(function(){
// Find first occurence of li that starts with letter typed
if ($(this).text().substr(0,1).toUpperCase() == char && $(this).text() != "Choose"){
charFound = true;
$('a.selected', $wrapper).removeClass('selected');
$(this).addClass('selected');
$select[0].selectedIndex = $(this).attr('index');
$($select[0]).trigger('change');
$that = $(this);
return false;
}
});
if (charFound == true){
// Scroll to selected value
$ul.scrollTo($('a.selected', $ul), 400);
}
}
//If Enter has been pressed, select the value
if(code == 13) {
$('span:eq(0)', $wrapper).html($that.html());
$ul.hide();
return false;
}
}
});
$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});