Call SignalR hub method with dynamically created button - javascript

I have a problem with button click does not firing when it dynamically created,
I know, here is the solution.
Question is this:
I am using SignalR. I must declare click event (to call some hub method) when chat hub is started. Please see below
button click works in this situation
$(document).on('click', "#chatlist li .gobtn", function (e) {
var id = $(this).closest("li").data("message-id");
});
But i should call it from here
$.connection.hub.start().done(function () {
//button click not fires here but it must be here
$('#chatlist li .gobtn').click(function () {
var id = $(this).closest("li").data("message-id");
chat.server.sendAnswer(id);
})
})
Please help if you have any idea to solve it.

If you change your code like below, i think it works
var chat;
var _sendAnswer;
$(function () {
var chat = $.connection.chatHub;
$.connection.hub.start().done(function () {
_sendAnswer = function sendAnswer(id) {
chat.server.sendAnswer(id);
}
});
$(document).on('click', "#chatlist li .gobtn", function (e) {
var id = $(this).closest("li").data("message-id");
if (_sendAnswer != undefined && typeof _sendAnswer == 'function') {
_sendAnswer(id);
}
});
});
I wish you good luck

Related

Click not triggered on Javascript function that submits to Facebook Pixel

The following code tracks the number of clicks on the element and then submits the result to Facebook Pixel. However, the event is not triggered for some reason.
Thought it's a variable scope problem, changed countClicks to global but it didn't change anything.
$(document).ready(function () {
if(window.location.href.indexOf("products") > -1) {
var countClicks = 0;
$(".product-single__thumbnail-image").click(function () {
countClicks++;
});
function firePixelSlideshowView() {
fbq('trackCustom', "ProductSlideshowImageView", {
imageView: countClicks,
});
}
window.onbeforeunload = function () {
firePixelSlideshowView();
return null;
}
}
});
I solved the problem by using jQuery unload() function instead of vanilla Javascript and it worked.

Module overwrite previous attached window mouseup event

I am currently working on a javascript module which open and close boxes, tooltip or similar, the function works great the only problem is when I call it twice on a page where the 'boxes' classes are different the window mouseup event will be overwritten and only one of the two module instances of boxes can now be closed after opening them.
var boxRevealer = (function () {
var buttons;
var boxes;
var element;
var drp_active = false;
var boxConstruct = function (btns, bxs) {
buttons = document.querySelectorAll(btns);
boxes = document.querySelectorAll(bxs);
boxEvents();
};
var boxEvents = function () {
buttons.forEach(function (e) {
e.addEventListener("click", function (ee) {
element = document.getElementById(e.getAttribute("data-drp"));
element.classList.toggle("displayn");
drp_active = true;
});
});
window.addEventListener("mouseup", function (e) {
if (drp_active === true) {
if (!e.target.classList.contains("filt_holy")) {
boxes.forEach(function (e) {
console.log("ELEMENT");
console.log(e);
e.classList.add("displayn");
});
}
}
}, false);
};
return {
boxConstruct: boxConstruct,
boxEvents: boxEvents
};
})();
Here is how i call the module
window.addEventListener("load", function(e){
boxRevealer.boxConstruct(".head_drp_btn", ".head_drp");
boxRevealer.boxConstruct(".mkt_drp_btn", ".mkt_drp");
});
So my question is, should I always name the boxes the same, or is there a work around?
Just remove the event before adding it, I think the same event is getting called twice.
So updated code will be as follows:
// Attach an event handler to <div>
e.addEventListener("mousemove", myFunction);
// Remove the event handler from <div>
e.removeEventListener("mousemove", myFunction);
And remove the window event as well before adding it.

Event listener not firing on click

I am creating a simple function to close a flash message div on click event, but my listener is not firing.
I wrote 3 different functions to try to get it working, but nothing is happening and Chrome console isnt telling me anything.
My first was in ES6 class style, this one:
class closeFlashMessages {
constructor () {
this.getFlashMessages = document.querySelector("#flash-messages");
this.addEventListeners();
}
close () {
console.log(this.getFlashMessages);
this.getFlashMessages.className = "hide";
}
addEventListeners () {
if(this.getFlashMessages)
this.getFlashMessages.addEventListener("click", this.close);
}
}
new closeFlashMessages();
My second was this:
(function (){
let getFlashMessages = document.querySelector("#flash-messages");
function close () {
console.log(getFlashMessages);
getFlashMessages.className = "hide";
}
function addEventListeners () {
getFlashMessages.addEventListener("click", function () {
close()
});
}
addEventListeners();
});
My last one is this:
(function (){
let getFlashMessages = document.getElementById("flash-messages");
getFlashMessages.addEventListener("click", close(getFlashMessages));
function close (id) {
console.log(getFlashMessages);
getFlashMessages.className = "hide";
}
});
My HTML:
<div id="flash-messages">
<div class="flash success">
<p>Recept byl přidán do nákupního seznamu.</p>
</div>
</div>
But none of them worked!! I dont understand
With the first two, I was getting undefined on my this.getFlashMessages also not sure why.
My solution is not in ES6
function Init(){
var id = document.getElementById('flash-messages');
var msg = document.querySelector('.flash');
id.addEventListener('click',function(){
msg.className = 'hide';
});
}
Init();
see demo here
I am not very much familiar with ES6.
But if I try similar code sample on a javascript it will be as given below and I hope it will be almost similar in ES6 aswell.
var getFlashMessages = document.getElementById("flash-messages");
getFlashMessages.addEventListener("click", function()
{
clicked(getFlashMessages);
});
function clicked(id){
console.log(id);
id.className = "hide";
}
Here, I am calling anonymous function, and its default argument will be event object as given in https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener.

jQuery toggle triggers effect instead of handler [duplicate]

$('.slideArrow').toggle(function (event) {
//some code
}, function (event) {
//some code
});
This works fine for content which are loaded on page-load.But the same function does not work for content loaded with ajax.It just does not intercept the click.
What should I do?
In an other scenario,i faced a same problem(not for toggle,for click) and sorted it this way.I dont know what to do for toggle?
$('.common-parent').on('click','.target-of-click',function(){
//some code
})
The flag method :
var flag = false;
$(document).on('click', '.slideArrow', function(event) {
if (flag) {
// do one thing
}else{
// do another thing
}
flag = !flag;
});
the data method
$(document).on('click', '.slideArrow', function(event) {
if ( $(this).data('flag') ) {
// do one thing
}else{
// do another thing
}
$(this).data('flag', !$(this).data('flag'));
});

jQuery Event Bubbling on wrong object

I'm still a little new to jQuery events.
I'm trying to write jQuery a wrapper/framework of the Asp.NET UpdatePanel that automatically tracks UpdatePanel async updates.
I want to be able to do something like
$("#myUpdatePanel").on("update", myFunc);
and have it run some handler with this as the updated UpdatePanel. I actually have this bit working.
I also want to be able run a function exactly once any time one or many UpdatePanels update.
$.updatePanel.on("update", myRunOnceFunc);
This is where I'm having issues.
I've defined my wrapper:
// wrap updatePanel reload functionality
$.updatePanel = (function () {
var prm;
var UpdatePanel = function () { };
UpdatePanel.prototype = { };
// initialize on $(document).ready()
$(function () {
prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm) {
prm.add_pageLoaded(function (s, e) {
$.each(e.get_panelsUpdated(), function () {
// call panel-specific update event handlers
$(this).trigger($.Event("update"));
});
// triggered once no matter how many panels were updated
$(UpdatePanel).trigger($.Event("update"));
});
}
});
return $(UpdatePanel);
})();
Then in my code that uses $.updatePanel:
$(function() { $.updatePanel.on("update", myRunOnceFunc); });
What I'm finding is that myRunOnceFunc is being run during both $(this).trigger($.Event("update")); and $(UpdatePanel).trigger($.Event("update"));.
Any ideas why and how to fix it?
I figured out what was wrong.
Rather than return $(UpdatePanel);, I needed to call return $(new UpdatePanel());. Then I needed to replace $(UpdatePanel).trigger(...) with $.updatePanel.trigger(...). Code below:
// wrap updatePanel reload functionality
$.updatePanel = (function () {
var prm;
var UpdatePanel = function () { }
UpdatePanel.prototype = { };
$(function () {
prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm) {
prm.add_pageLoaded(function (s, e) {
$.each(e.get_panelsUpdated(), function () {
$(this).trigger($.Event("update"));
});
// triggered once no matter how many panels were updated
$.updatePanel.trigger($.Event("update"));
});
}
});
return $(new UpdatePanel());
})();

Categories