jQuery .on() event doesn't work for dynamically added element - events

I'm making a project where a whole div with buttons is being inserted dynamically when user click a button, and inside that div there's a button, which when the user click on it, it does something else, like alerting something for example.
The problem is when i press on that button in the dynamically added div, nothing happens. The event doesn't fire at all.
I tried to add that div inside the HTML and try again, the event worked. So i guess it's because the div is dynamically added.
The added div has a class mainTaskWrapper, and the button has a class checkButton.
The event is attached using .on() at the end of script.js file below.
Here's my code :
helper_main_task.js : (that's the object that adds the div, you don't have to read it, as i think it's all about that div being dynamically added, but i'll put it in case you needed to)
var MainUtil = {
tasksArr : [],
catArr : ["all"],
add : function(){
var MTLabel = $("#mainTaskInput").val(), //task label
MTCategory = $("#mainCatInput").val(), //task category
MTPriority = $("#prioritySlider").slider("value"), //task priority
MTContents = $('<div class="wholeTask">\
<div class="mainTaskWrapper clearfix">\
<div class="mainMarker"></div>\
<label class="mainTaskLabel"></label>\
<div class="holder"></div>\
<div class="subTrigger"></div>\
<div class="checkButton"></div>\
<div class="optTrigger"></div>\
<div class="addSubButton"></div>\
<div class="mainOptions">\
<ul>\
<li id="mainInfo">Details</li>\
<li id="mainEdit">Edit</li>\
<li id="mainDelete">Delete</li>\
</ul>\
</div>\
</div>\
</div>');
this.tasksArr.push(MTLabel);
//setting label
MTContents.find(".mainTaskLabel").text(MTLabel);
//setting category
if(MTCategory == ""){
MTCategory = "uncategorized";
}
MTContents.attr('data-cat', MTCategory);
if(this.catArr.indexOf(MTCategory) == -1){
this.catArr.push(MTCategory);
$("#categories ul").append("<li>" + MTCategory +"</li>");
}
$("#mainCatInput").autocomplete("option", "source",this.catArr);
//setting priority marker color
if(MTPriority == 2){
MTContents.find(".mainMarker").css("background-color", "red");
} else if(MTPriority == 1){
MTContents.find(".mainMarker").css("background-color", "black");
} else if(MTPriority == 0){
MTContents.find(".mainMarker").css("background-color", "blue");
}
MTContents.hide();
$("#tasksWrapper").prepend(MTContents);
MTContents.slideDown(100);
$("#tasksWrapper").sortable({
axis: "y",
scroll: "true",
scrollSpeed : 10,
scrollSensitivity: 10,
handle: $(".holder")
});
}
};
script.js : (the file where the .on() function resides at the bottom)
$(function(){
$("#addMain, #mainCatInput").on('click keypress', function(evt){
if(evt.type == "click" || evt.type =="keypress"){
if((evt.type =="click" && evt.target.id == "addMain") ||
(evt.which == 13 && evt.target.id=="mainCatInput")){
MainUtil.add();
}
}
});
//Here's the event i'm talking about :
$("div.mainTaskWrapper").on('click', '.checkButton' , function(){
alert("test text");
});
});

It does not look like div.mainTaskWrapper exist.
From the documentation (yes, it is actually bold):
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page.
[...]
By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
You might want to bind it to #tasksWrapper instead:
$("#tasksWrapper").on('click', '.checkButton' , function(){
alert("test text");
});

You need to specify a selector with on (as a parameter) to make it behave like the old delegate method. If you don't do that, the event will only be linked to the elements that currenly match div.mainTaskWrapper (which do not exists yet). You need to either re-assign the event after you added the new elements, or add the event to an element that already exists, like #tasksWrapper or the document itself.
See 'Direct and delegate events' on this page.

I know this is an old post but might be useful for anyone else who comes across...
You could try:
jQuery('body')on.('DOMNodeInserted', '#yourdynamicallyaddeddiv', function () {
//Your button click event
});
Here's a quick example - https://jsfiddle.net/8b0e2auu/

Related

reactJS - Adding an event handler to an element which might, or might not exist at this time

I am not allowed to answer questions yet, but I feel that since this issue has taken me some days to resolve, I should post the solution the only way I can - as a question.
If you have a better solution then please include that in your reply.
Until an element is rendered it is not in the DOM so if you add an event listener to the element in your code you will get an error (element value null).
But you can add a listener to the root element, which is always there. WHen the event is triggered you can then retrieve the className and ID of the element involved in your event-handler.
Code:
var rootElement = document.getElementById('root');
console.log(rootElement);
rootElement.addEventListener('click', rootElementClicked);
console.log('event listener added to root element');
function rootElementClicked(event) {
event.preventDefault();
const { name, value } = event.target;
console.log("Root element clicked with [" + event.target.className, event.target.id);
}
/code
So, the event-listener is app-wide, so a click anywhere will call the event-handler function. Then in the code for that function, the element class and ID will tell you what was clicked.
Note the event.preventDefault(); line - it prevents a refresh of the web page, otherwise the target class & ID are returned as "undefined"
In React you shouldn't need to addEventListener manually since you can use onClick. However if you would like to manually attach click handler on an HTML element in React you can use React Ref. If you pass a ref object to React with <div ref={myRef} /> React will set its .current property to the corresponding DOM node whenever that node changes.
Example: https://codesandbox.io/s/react-hooks-useref-xfvlb
const App = () => {
const elementRef = useRef();
useEffect(() => {
elementRef.current.addEventListener('click', handleOnClick);
},[elementRef])
const handleOnClick = () => {
alert("click")
}
return (
<div className="App">
<div ref={elementRef}>
click on me
</div>
</div>
);
}

How to find selected tab on KendoTabStrip on page load?

I am using Kendo UI MVC and i have a kendoTabStrip on acshtml page. By default I am selecting the first tab on page load. All other tabs are loaded dynamically using AJAX.
Issue: I am trying to find the selected tab so i can find its children?
one way to find active tab is by calling select() method without parameter, or anotherway is by checking classname 'k-state-active' however both methods doesnt work
<section class="tpt-tabstrip">
#(Html.Kendo().TabStrip()
.Name("MyTabStrip")
.Animation(false)
.Items(items =>
{
foreach (var revision in Model.MyCollection)
{
items.Add()
.Text(revision.Name)
.LoadContentFrom("MyActionMethod", "MyController", Model.ID);
}
})
)
</section>
<script src="~/Scripts/MyScript.js"></script>
Note that above in cshtml that the script tag is at the end of the page.
Below is the script code
$(function(){
var tabStrip = $("#MyTabStrip").getKendoTabStrip();
if (tabStrip != null && tabStrip.tabGroup.length > 0) {
tabStrip.select(0); // this line is getting executed for sure
}
// the line below returns -1 here why?????
var index = tabStrip.select().index();
// another way to find active tab is by checkikng class name 'k-state-active' however it didnt work either.
// jQuery couldnt find any element with class 'k-state-active'
$('.k-state-active')
})
UPDATE1
The activate event of tabstrip would not work for me because it get fired each time i select tab. I need an event which gets fired only once. Ultimately i want to find NumericTextBox controls on selected tab and attach 'change' event handlers to those controls. like below
$(function(){
var tabStrip = $('#MyTabStrip').data("kendoTabStrip");
tabStrip.bind('activate', function (e) {
$('[data-role="numerictextbox"]').each(function(){
$(this).getKendoNumericTextBox().bind("change",function(e){
alert('changed');
})
})
});
})
here the change event handler will get attach to NumericTextBox everytime i select the tab
$('.k-state-active') works fine it will return the two elements from DOM. You are trying to select element in $(document).ready that's the reason you are not getting element as tab control is not rendered yet.
Try to write your code onActivate event of kendo tab strip control.
OnActivate event is triggered after a tab is being made visible and its animation complete. Before Q2 2014 this event was invoked after tab show, but before the end of the animation. This event is triggered only for tabs with associated content.
See more at http://docs.telerik.com/kendo-ui/api/javascript/ui/tabstrip#events-activate
1st Tab name
<li class="k-item k-state-default k-first k-tab-on-top k-state-active" role="tab" aria-controls="RoleTabs-1" style="" aria-selected="true">
<span class="k-loading k-complete k-progress"></span>
<a class="k-link">Tab Name</a>
2nd Tab Content
<div class="k-content k-state-active" id="RoleTabs-1" style="display: block; height: auto; overflow: auto; opacity: 1;" role="tabpanel" aria-expanded="true">

kendo ui grid programatically hide and show the filterable row

I have a kendo grid with filterable = true, mode=row.
I would like a way to have a button click, fire an event that will toggle hiding and showing the filter row.
Right now, I have it working by editing the innerHTML, but this is not what I want to do in the end, for several reasons.
1) I need to have a saved version of the filter row values before they are removed.
2) After they are removed and re-added they will not work
...
many other reasons, just bad practice and there has to be a better way.
A button that fires the event: toggleFilterClick:
<script type="text/x-kendo-template" id="gridFilter">
<button type="button" class="k-button" id="kendoFilterButton" data-click="toggleFilter"><span class="k-icon k-i-funnel"></span>Filter On/Off</button>
</script>
The Javascript code:
//Gets the innerHTML values before they are removed
var filterRowValues = $(".k-filter-row")[0].innerHTML;
//fired when the button is clicked
var toggleFilterClick = $('#kendoFilterButton').on("click", function () {
if ($(".k-filter-row")[0].innerHTML == '')
{
$(".k-filter-row")[0].innerHTML = filterRowValues;
}
else
{
$(".k-filter-row")[0].innerHTML = '';
}
});
Any thoughts suggestions would be appreciated/
I would just like to hide the actual filter row in the header
I'm not sure if i get the point but if you just want to hide it just simply remove everything except$(".k-filter-row").show(); and $(".k-filter-row").hide();. I create an example where when i hide the filter, the filter condtion will removed, but when it showed again the grid will refiltered with the previous value used to filter
$("#toggle").kendoButton({
click:function(){
if($(".k-filter-row").css("display") == "none"){
$(".k-filter-row").show();
//show again filter and execute previous filter condition
$("#grid").data("kendoGrid").dataSource.filter({field:"ShipName",operator:"contains",value:vm.get("filterOptions.ShipName").toString()});
$("#grid").data("kendoGrid").dataSource.filter({field:"OrderID",operator:"eq",value:vm.get("filterOptions.OrderID")});
}else{
//store the previous filter value
//autocomplete
vm.set("filterOptions.ShipName",$("input[data-role='autocomplete']").data("kendoAutoComplete").value());
vm.set("filterOptions.OrderID",$("input[data-role='numerictextbox']").data("kendoNumericTextBox").value());
//hide filter row
$(".k-filter-row").show();
//to reset filter of the grid when filterable hidden
$("#grid").data("kendoGrid").dataSource.filter({});
}
}
});
See the details in action
DEMO
Have you tried just hiding the row instead of removing it?
//fired when the button is clicked
var toggleFilterClick = $('#kendoFilterButton').on("click", function () {
if ($(".k-filter-row").is(":visible")){
$(".k-filter-row").hide();
}
else{
$(".k-filter-row").show();
}
});

AngularJS directive toggle menu preventing default for other directive

So I made a directive for a toggle (drop down) menu in AngularJS. I used the directive for multiple items within the page but I have a small problem. When one item is open and I click another one I want the previous one to close. The event.preventDefault and event.stopPropagation stops the event for the previous item and doesn't close it. Any ideas on how to fix this? Is there a way to perhaps only stop the event within the scope?
app.directive('toggleMenu', function ($document) {
return {
restrict: 'CA',
link: function (scope, element, attrs) {
var opened = false;
var button = (attrs.menuButton ? angular.element(document.getElementById(attrs.menuButton)) : element.parent());
var closeButton = (attrs.closeButton ? angular.element(document.getElementById(attrs.closeButton)) : false);
var toggleMenu = function(){
(opened ? element.fadeOut('fast') : element.fadeIn('fast'));
};
button.bind('click', function(event){
event.preventDefault();
event.stopPropagation();
toggleMenu();
opened = ! opened;
});
element.bind('click', function(event){
if(attrs.stayOpen && event.target != closeButton[0]){
event.preventDefault();
event.stopPropagation();
}
});
$document.bind('click', function(){
if(opened){
toggleMenu();
opened = false;
}
});
}
};
And here's a Fiddle: http://jsfiddle.net/JknUJ/5/
Button opens content and content should close when clicked outside the div. When clicked on button 2 however content 1 doesn't close.
Basic idea is that you need to share the state between all your dropdown submenus, so when one of them is shown, all others are hidden. The simpliest way of storing state (such as opened or closed) are... CSS classes!
We'll create a pair of directives - one for menu, and another for sumbenu. It is more expressive that just divs.
Here is out markup.
<menu>
<submenu data-caption="Button 1">
Content 1
</submenu>
<submenu data-caption="Button 2">
Content 2
</submenu>
</menu>
Look how readable is it! Say thanks to directives:
plunker.directive("menu", function(){
return {
restrict : "E",
scope : {},
transclude : true,
replace : true,
template : "<div class='menu' data-ng-transclude></div>",
controller : function ($scope, $element, $attrs, $transclude){
$scope.submenus = [];
this.addSubmenu = function (submenu) {
$scope.submenus.push(submenu);
}
this.closeAllSubmenus = function (doNotTouch){
angular.forEach($scope.submenus, function(submenu){
if(submenu != doNotTouch){
submenu.close();
}
})
}
}
}
});
plunker.directive("submenu", function(){
return {
restrict : "E",
require : "^menu",
scope : {
caption : "#"
},
transclude : true,
replace : true,
template : "<div class='submenu'><label>{{caption}}</label><div class='submenu-content' data-ng-transclude></div></div>",
link : function ($scope, $iElement, $iAttrs, menuController) {
menuController.addSubmenu($scope);
$iElement.bind("click", function(event){
menuController.closeAllSubmenus($scope);
$iElement.toggleClass("active");
});
$scope.close = function (){
$iElement.removeClass("active");
}
}
}
});
Look thar we restricted them to HTML elements (restrict : "E"). submenu requires to be nested in menu (require : "^menu"), this allows us to inject menu controller to submenu's link function. transclude and replace controls the position of original markup in compiled HTML output (replace=true means that original markup will be replaced with compiled, transclude inserts parts of original markup to compiled output).
When we've done with this, we just say to menu close all your child menus! and menu iterates over submenus, forcing them to close.
We are adding childs to menu controller in addSubmenu function. It is called in submenus link function, thus every compiled instance of submenu adds itself to menu. Now, closing all submenus is as easy as iterating over all children, this is done by closeAllSubmenus in menu controller.
Here is a full Plunker to play with.

CKEDITOR - how to add permanent onclick event?

I am looking for a way to make the CKEDITOR wysiwyg content interactive. This means for example adding some onclick events to the specific elements. I can do something like this:
CKEDITOR.instances['editor1'].document.getById('someid').setAttribute('onclick','alert("blabla")');
After processing this action it works nice. But consequently if I change the mode to source-mode and then return to wysiwyg-mode, the javascript won't run. The onclick action is still visible in the source-mode, but is not rendered inside the textarea element.
However, it is interesting, that this works fine everytime:
CKEDITOR.instances['editor1'].document.getById('id1').setAttribute('style','cursor: pointer;');
And it is also not rendered inside the textarea element! How is it possible? What is the best way to work with onclick and onmouse events of CKEDITOR content elements?
I tried manually write this by the source-mode:
<html>
<head>
<title></title>
</head>
<body>
<p>
This is some <strong id="id1" onclick="alert('blabla');" style="cursor: pointer;">sample text</strong>. You are using CKEditor.</p>
</body>
</html>
And the Javascript (onclick action) does not work. Any ideas?
Thanks a lot!
My final solution:
editor.on('contentDom', function() {
var elements = editor.document.getElementsByTag('span');
for (var i = 0, c = elements.count(); i < c; i++) {
var e = new CKEDITOR.dom.element(elements.$.item(i));
if (hasSemanticAttribute(e)) {
// leve tlacitko mysi - obsluha
e.on('click', function() {
if (this.getAttribute('class') === marked) {
if (editor.document.$.getElementsByClassName(marked_unique).length > 0) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked_unique);
}
} else if (this.getAttribute('class') === marked_unique) {
this.removeAttribute('class');
} else {
this.setAttribute('class', marked);
}
});
}
}
});
Filtering (only CKEditor >=4.1)
This attribute is removed because CKEditor does not allow it. This filtering system is called Advanced Content Filter and you can read about it here:
http://ckeditor.com/blog/Upgrading-to-CKEditor-4.1
http://ckeditor.com/blog/CKEditor-4.1-Released
Advanced Content Filter guide
In short - you need to configure editor to allow onclick attributes on some elements. For example:
CKEDITOR.replace( 'editor1', {
extraAllowedContent: 'strong[onclick]'
} );
Read more here: config.extraAllowedContent.
on* attributes inside CKEditor
CKEditor encodes on* attributes when loading content so they are not breaking editing features. For example, onmouseout becomes data-cke-pa-onmouseout inside editor and then, when getting data from editor, this attributes is decoded.
There's no configuration option for this, because it wouldn't make sense.
Note: As you're setting attribute for element inside editor's editable element, you should set it to the protected format:
element.setAttribute( 'data-cke-pa-onclick', 'alert("blabla")' );
Clickable elements in CKEditor
If you want to observe click events in editor, then this is the correct solution:
editor.on( 'contentDom', function() {
var element = editor.document.getById( 'foo' );
editor.editable().attachListener( element, 'click', function( evt ) {
// ...
// Get the event target (needed for events delegation).
evt.data.getTarget();
} );
} );
Check the documentation for editor#contentDom event which is very important in such cases.

Resources