Extra click after dynamically added HTML elements via jQuery - javascript

I add some html dynamically in data.html
<div class="d-flex " id="deviceSeearchRecords">
<div class="p-2 flex-grow-1 ">
<button type="button" class="btn deviceName " data-href="#Url.Content(string.Format(" ~/Devices/Details/{0} ", #item.ID))">
#item.FullName
</button>
</div>
</div>
After this I assume to use click event like this.
$('#searchResultContainer').html('');
$.getJSON('#Url.Action("Search", "Devices")', {
s: $('#searchStr').val()
},
function(data) {
if (data.success === true) {
$('#searchResultContainer').append(data.html);
$(document).on('click', '.deviceName', function(e) {
e.preventDefault();
e.stopPropagation();
// console.log('deviceName ' + $(this).data('href'));
window.location.href = $(this).data('href');
});
}
});
But when I click first time then nothing happens. On second click it works as it should.
I have tried to use focus() on div but if does not help.
This approach does not help as well jquery functions inside of dynamically generated html not working
What do I missing here?

Move your code to the outside
$(document).on('click', '.deviceName', function(e) {
e.preventDefault();
e.stopPropagation();
// console.log('deviceName ' + $(this).data('href'));
window.location.href = $(this).data('href');
});

Thanks to all!
I found my solution here
Is it possible to focus on a <div> using JavaScript focus() function?
So I just use a regular <a> within data.html and after this focus on the div with dynamically added data. And one click works!
$('#searchResultContainer').html('');
$.getJSON('#Url.Action("Search", "Devices")', {
s: $('#searchStr').val()
},
function(data) {
if (data.success === true) {
if (data.success === true) {
$('#searchResultContainer').html(data.html);
window.location.hash = '#searchResultContainer';
}
}
});

Related

localStorage onload show my selected div?

how show hide div with localStorage, example if i select IT, onload show div IT.
my js code
itlang = document.getElementById('LangIT');
itlang.onclick = function(event) {
localStorage.setItem('a_avlang', '1');
$('.avlan').hide();
$('.av-it').show();
};
if (a_avlang === '1') {
localStorage.getItem('a_avlang', '1');
$('.avlan').hide();
$('.av-it').show();
} else {
localStorage.setItem('a_avlang', '0');
$('.av-it').hide();
}
}
my buttons html
<a class="avlangbuttons" href="#it" id="LangIT" target="_self">IT</a>
<a class="avlangbuttons" href="#en" id="LangEN" target="_self">EN</a>
My div to Show/hide html
<div class="avlan av-it" style="display:none;">
IT
</div>
<div class="avlan av-en">
EN
</div>
You have some invalid syntax.
localStorage.getItem('a_avlang', '1'); is invalid, there is only one parameter on getItem
Why use getElementById and onclick when you have jQuery?
My guess is you mean
function toggleAV(lang) {
$('.av-it').toggle(lang=="LangIT");
$('.av-en').toggle(lang=="LangEN");
localStorage.setItem('a_avlang', lang); // saves LangEN or LangIT
}
$(function() { // onload
$('.avlangbuttons').on("click", function(event) {
event.preventDefault(); // stop the click
toggleAV(this.id);
});
toggleAV(localStorage.getItem('a_avlang') || "LangEN"); // if exists otherwise english
});
Alternatively use data-attributes instead of parsing the ID

How to disable anchor tag onclick events inside div element?

I have html content as given below.
<div>
Link 1
Link 1
Link 1
Link 1
Link 1
</div>
Problem:
When I click on any link, in the onClick function I will make one ajax call.
I just want to disable all the onClick events of a tag(or disable the entire div and all of its child elements) till I get the ajax response after getting the response I need to re-enable all the a tag onclick events.
Is there any way achieve the same?
You can use beforeSend callback of jqXHR where you can disable all anchor tag and
jqXHR.always() callback where you will enable all anchor tag .
go through Jquery Ajax Documentation
Thanks for so many solutions.
I have found a very simple solution.
Solution:
You can use the CSS property pointer-events to disable the click event on any element:
https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
// To disable:
document.getElementById('id').style.pointerEvents = 'none';
// To re-enable:
document.getElementById('id').style.pointerEvents = 'auto';
// Use '' if you want to allow CSS rules to set the value
Thanks,
Dixit
Link 1
someFunction(){
//some code here
$.get('test.aspx', function(data){
//do something here
})
return false;
}
Check This DEMO
You can use .ajaxStart() & .ajaxStop() JQUERY events to do this. You can create a different css to disable the anchor tag as below :
$('a[href]').each(function () {
var $this = $(this);
if ($this.attr('href') && $this.attr('href') != '') {
$(this).attr('data-href', $(this).attr('href'));
$(this).removeAttr('href');
}
});
and while enabling it back
$('a[data-href]').each(function () {
var $this = $(this);
if ($this.attr('data-href') && $this.attr('data-href') != '') {
$(this).attr('href', $(this).attr('data-href'));
$(this).removeAttr('data-href');
}
});
This will remove your href and create a custom attribute. So your click event will not work on anchor tag.
set a flag for active status
function someFunction(){
var status = $('#parentDiv').attr('data-active');
if(!status){
$("#parentDiv").attr('data-active',true);
//make ajax call
$.ajax("url", {
success: function(data) {
$("#parentDiv").attr('data-active',false);//make false when done
}
});
}
}
<div id="parentDiv" data-active="false">
Link 1
Link 1
Link 1
Link 1
Link 1
</div>
Note: This is an alternate solution. IMHO kedar kamthe's solution is the best way to solve this problem
You can try this:
1) Add class to div:
<div class="myDiv">
Link 1
Link 1
Link 1
Link 1
Link 1
</div>
2) Hide div when ajax starts and show div in success of ajax:
$(".myDiv").css('opacity','0.25');// blur div when ajax starts
$.ajax("test.php", {
success: function(data) {
$(".myDiv").css('opacity','1');// display div as ajax complete
},
error: function() {
alert('An error occurred');
}
});
});
you can use beforeSend to set a callback function to disable all elements. and enable them in success. You can add a function to disable/enable those element. add an id to the div.
$.ajax(
url: "your url",
beforeSend: function( xhr ) {
disabledFields(true);
},
success: function(){
disabledFields(false);
},
error: function(){
disabledFields(false);
});
//
function disabledField(isDisabled)
{
$("#myDiv").find("a").each(function(){
if (isDisabled)
{
$(this).attr("disabled", "disabled");
}
else
{
$(this).removeAttr("disabled");
}
});
}

jquery div not respnding to other javascript/jquery methods

I have added one div inside a div using $(select).append() method but the I want it to close it on click on image so i hav added image and an another $(select).button().click( { $(select).hide() }); but on clicking the close image nothing happens....
$(document).ready(function() {
$("#subCre").click(function() {
cust = $("#customer").val();
address = $('#address').val();
phone = $('#phone').val();
amt = $('#initamount').val();
user = '<%= session.getAttribute("user").toString()%>';
type = '<%=session.getAttribute("type").toString()%>';
alert(cust + address + phone + amt + user + type);
$.post("../processor/proc2.jsp",
{
customer: cust,
address: address,
phone: phone,
initamount: amt,
user: user,
type: type
},
function(data, status) {
if (status === "success") {
if(data.length == 11) {
$("#SystemMessages").append('<div class="Msg draggable"><img class="close" src="../mime/close.png">Account Added</div>'); // **Here one div
} else {
$("#SystemMessages").append('<div class="errorMsg draggable"><img class="close" src="../mime/close.png">'+ data + '</div>'); //** here 2nd div
}
$("#customer").val("");
$('#address').val("");
$('#phone').val("");
$('#initamount').val("");
}
});
$(".close").button().click(function() {
$(".close").parent().css("visibility", "hidden");
});
});
You need to use event delegation for dynamically appended elements
$('#SystemMessages').on('click','.close',function(){
$(this).parent().css("visibility", "hidden");
});
Event delegation ---> https://learn.jquery.com/events/event-delegation/
Since you have dynamically added .close element to the existing HTML, you need to delegate it using on event handler
$(".close").button();
$("#SystemMessages").on('click', ".close", function() {
$(".close").parent().css("visibility", "hidden");
});
Simply use the following code
$('.close').live('click',function(){
$(this).parent().hide();
});
It will definitely work, let me know if it worked.
.live() being deprecated in jQuery version 1.7 and removed in version 1.9, so you can use .on() method in the following manner
$(document).on('click','.close',function(){
$(this).parent().hide();
});

html div onclick event

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js code
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.
JSFiddle
what is wrong with my code? please help me out.
The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
DEMO
Try following :
$('.expandable-panel-heading').click(function (e) {
if(e.target.nodeName == 'A'){
markActiveLink(e.target)
return;
}else{
alert('123');
}
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
Here is the working demo : http://jsfiddle.net/JVrNc/4/
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Demo
You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway
Test the click on the div and examine the target
Live Demo
$(".expandable-panel-heading").on("click",function (e) {
if (e.target.id =="ancherComplaint") { // or test the tag
e.preventDefault(); // or e.stopPropagation()
markActiveLink(e.target);
}
else alert('123');
});
function markActiveLink(el) {
alert(el.id);
}
I would have used stopPropagation like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>
http://jsfiddle.net/NXML7/1/
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});

select the Div without specific content

Q:
I have the following case :
Div contains a link , i wanna to just select the div without the link,i mean ,when clicking on the div i wanna specific action differs from clicking the link.through some JQuery.
the structure i work on is:(by firebug)
<div class ="rsAptContent">
sql
<a class = "rsAptDelete" href = "#" style ="visibility: hidden;">Delete</a>
</div>
the JQuery code:
<script type="text/javascript">
$(document).ready(function() {
$(".rsAptContent").click(function(e) {
ShowDialog(true);
e.preventDefault();
});
});
function ShowDialog(modal) {
$("#overlay").show();
$("#dialog").fadeIn(300);
if (modal) {
$("#overlay").unbind("click");
}
else {
$("#overlay").click(function(e) {
HideDialog();
});
}
}
function HideDialog() {
$("#overlay").hide();
$("#dialog").fadeOut(300);
}
</script>`
when i click on the link ,i don't want to execute the Jquery code , how to select the div without the link in.
thanks in advance
Are you looking for something like the stopPropagation() code?
$(".rsAptContent").click(function(e) {
e.stopPropagation();
ShowDialog(true);
return false;
});
});
That should stop the link from executing.
http://api.jquery.com/event.stopPropagation/
Edit: Distinguish between clicking the link and clicking on any part of the content except the link
$(".rsAptContent").click(function(e) {
var $target = $(e.target);
if($target.is(a){
// It's the link.
}else{
// else it's not
}
});
});
Check for the clicked target element than perform action
to get info about which element is click use below script
function whichElement(event){
var tname
tname=event.srcElement.tagName
alert("You clicked on a " + tname + " element.")
}
Try this:
$(".rsAptContent").click(function(e) {
if($(e.target).hasClass('rsAptDelete')) return false;
ShowDialog(true);
e.preventDefault();
});
});
If the target is the link the event is cancelled;
If you already have a click handler on the delete link, then just stop the event propagation there by using stopPropagation().
$(".rsAptDelete").click(function(e) {
e.stopPropagation();
});

Categories

Resources