I'm trying to transform my code into a more plugin type of code, so everything will be separated, in case I change class names in the future.
For some reason, in my code, I get Cannot read property 'dropdown' of undefined.
My guess is, the function Navigation.bindEvents() runs before I set the config, so It can't find it... But I don't know how to solve it.
Here's my Navigation.js file:
let Navigation = {
config: {},
init(config) {
this.config = config;
this.bindEvents();
},
bindEvents() {
$(this.config.trigger).on('click', this.toggleNavigation);
$(document).on('click', this.hideAllDropdowns);
},
toggleNavigation(event) {
// Store the current visible state
var visible = $(this).siblings(this.config.trigger).hasClass('visible');
// Hide all the drop downs
this.hideAllDropdowns();
// If the stored state is visible, hide it... Vice-versa.
$(this).siblings(this.config.content).toggleClass('visible', !visible);
event.preventDefault();
event.stopPropagation();
},
hideAllDropdowns() {
$(this.config.dropdown + ' ' + this.config.content).removeClass('visible');
}
}
export default Navigation;
And here's my app.js file which I run all the init functions.
window.$ = window.jQuery = require('jquery');
import Navigation from './layout/navigation.js';
Navigation.init({
dropdown: '.dropdown',
trigger: '.dropdown-trigger',
content: '.dropdown-content'
});
I guess you got problem with the scope $(document).on('click', this.hideAllDropdowns);
Let's try
bindEvents() {
$(this.config.trigger).on('click', this.toggleNavigation);
$(document).on('click', this.hideAllDropdowns.bind(this));
},
UPDATE:
bindEvents() {
$(this.config.trigger).bind('click', {self:this}, this.toggleNavigation);
$(document).on('click', this.hideAllDropdowns.bind(this));
},
And replace all this.config by event.data.self inside toggleNavigation function
this in the context of toggleNavigation refers to the clicked element.
That is why you can do $(this).siblings(...) to get the sibling elements.
You need to have a reference to the Navigation object. Perhaps you can use the on syntax that allows you to pass extra data $(this.config.trigger).on('click', this, this.toggleNavigation);
Then rewrite the handler
toggleNavigation(event) {
//get the navigation reference
var nav = event.data;
// Store the current visible state
var visible = $(this).siblings(nav.config.trigger).hasClass('visible');
// Hide all the drop downs
nav.hideAllDropdowns();
// If the stored state is visible, hide it... Vice-versa.
$(this).siblings(nav.config.content).toggleClass('visible', !visible);
event.preventDefault();
event.stopPropagation();
},
The behavior of this is one of the hardest things to understand in JavaScript. Here this is obviously dynamic, which means that its value depends on where your method has been called...
let module = {
config() {
console.log(`config(): 'this' is 'module' ---> ${Object.is(this, module)}`);
console.log(`config(): 'this' is 'document' ---> ${Object.is(this, document)}`);
},
init() {
console.log(`init(): 'this' is 'module' ---> ${Object.is(this, module)}`);
console.log(`init(): 'this' is 'document' ---> ${Object.is(this, document)}`);
module.config();
}
};
$(document).ready(module.init);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
With x-tag I am trying to find a way to extend every html element that I put is:"ajax-pop" attribute.
What I want to do is when I click an element with is:"ajax-pop" attribute I will do some dynamic ajax loads. It will be a good starting point for me to develop a manageble system.
I know I can do it with some different ways but I am wondering is there a way to do it like this way extends:'every single native html element'
xtag.register('ajax-pop', {
extends: 'WHAT SHOULD I WRITE HERE???',
lifecycle: {
created: function () {
},
inserted: function () {
},
removed: function () { },
attributeChanged: function () { }
},
methods: {
someMethod: function () { }
},
accessors: {
popUrp: {
attribute: {
name: "pop-url"
}
},
},
events: {
tap: function () { },
focus: function () { }
}
});
Type extensions must be defined element by element. A single custom element cannot extend multiple standard elements.
For, each custom element owns it own prototype, that can't be reused.
If you want to extend a button (for example), you have to write in JavaScript :
xtag.register('ajax-pop', {
extends: 'button',
...
And, in the HTML page:
<button is="ajax-pop">
...
You can do this using x-tag's delegate pseudo, and by adding a data- attribute to elements you wish to have this behavior:
<article data-pop="/path/to/content.html"></article>
And your JavaScript would be something like this:
xtag.addEvent(document.body, 'tap:delegate([data-pop])', function (e) {
var uri = this.getAttribute('data-pop');
$.get(uri).done(function (res) {
this.innerHTML = res;
}.bind(this));
});
Here's a codepen example:
http://codepen.io/jpecor-pmi/pen/Vexqyg
I believe you're going about using x-tag the wrong way. X-tag is meant to be used to implement entirely new tags; what you're trying to do is simply modify different pre-existing DOM elements. This can easily be done in pure javascript or more easily in jquery by assigning each desired element a shared class.
I'm trying to create a jQuery control using the widget factory. The idea is that I turn a button into a jQuery button, give it an icon, and register the click event for that button such that when invoked, it displays a calendar control on a textbox, whose id is passed in as an option to the widget method:
$.widget("calendarButton", {
options: {
textFieldId: ''
},
_create: function () {
this.element.button(
{
icons: {
primary: "ui-icon-calendar"
}
}).click(function () {
if (this.options.textFieldId != '') {
$(this.options.textFieldId).datetimepicker('show');
return false;
}
});
}
});
The problem with this however, is that this.options is undefined when the click handler is invoked; which makes sense since the method has a different scope. So I tried to see if there is a way to define a "static" variable which then can be accessed inside the callback method. I found this answer that explained how to create variables inside a wrapper function like this:
(function ($) {
var $options = this.options;
$.widget("calendarButton", {
options: {
textFieldId: ''
},
_create: function () {
this.element.button(
{
icons: {
primary: "ui-icon-calendar"
}
}).click(function () {
if ($options.textFieldId != '') {
$($options.textFieldId).datetimepicker('show');
return false;
}
});
}
});
})(jQuery);
But it still reports that $options is undefined. Is there a way to achieve this? I'm trying to avoid requiring the callback function be passed in since it'll be pretty much the same for all instances. Any help is appreciated.
After playing with it for a few hours, I finally came across the jQuery Proxy method which is exactly what I was looking for. I changed the code a little bit to look like this:
$.widget("calendarButton", {
options: {
textFieldId: ''
},
_create: function () {
this.element.button(
{
icons: {
primary: "ui-icon-calendar"
}
}).on("click", $.proxy(this._clickHandler, this));
},
_clickHandler: function () {
if (this.options.textFieldId != '') {
$(this.options.textFieldId).datetimepicker('show');
}
}
});
Notice that instead of implementing the click callback directly, I'm essentially creating a delegate that points to my private _clickHandler function, which itself runs on the same context as the $.widget() method (since the second argument of $.proxy(this._clickHandler, this) returns $.widget()'s context) hence availablity of the options variable inside the method.
I am currently adding flagging functionality to a project of mine, and I can't get jQuery's $(this) selector to work.
The goal of this is to change the text in the div from flag to flagged when the user clicks it, and the ajax query runs successfully. My HTML/PHP is:
<div class="flag" post_to_flag='".$post_to_flag."'>Flag</div>
And my javascript that deals with the div is:
$('.flag').live('click', function () {
$.post('../php/core.inc.php', {
action: 'flag',
post_to_flag: $(this).attr('post_to_flag')
}, function (flag_return) {
if (flag_return == 'query_success') {
$(this).text('flagged');
} else {
alert(flag_return);
}
});
});
I can't replace the text with flagged, but if I replace the this selector with the .flag selector, it will replace everything with the class of flag on the page.
I have checked, and the $(this) selector is getting the attribute of 'post_to_flag' just fine. Why is this happening, and how can I fix it?
You should add a context variable:
$('.flag').live('click', function () {
var $context = $(this);
$.post('../php/core.inc.php', {
action: 'flag',
post_to_flag: $context.attr('post_to_flag')
}, function (flag_return) {
if (flag_return == 'query_success') {
$context.text('flagged');
} else {
alert(flag_return);
}
});
});
You are calling multiple functions within your jQuery selection call. When you go into that $.post() function, your scope changes. this now refers to a different scope from when you were inside one().
#Moak's suggestion, if you set a variable to a jQuery object, it's probably best to denote the variable with a beginning $ just for potential clarity for future readers or yourself.
this inside the ajax callback is not the element, but it is the Ajax object itself.
You can use $.proxy to pass in the context.
Ref $.proxy
$('.flag').live('click', function () {
$.post('../php/core.inc.php',
{action: 'flag', post_to_flag: $(this).attr('post_to_flag')},
$.proxy(function(flag_return) {
if(flag_return == 'query_success'){
$(this).text('flagged'); //Now this here will represent .flag
}else{
alert(flag_return);
}
},this)); //Now here you are passing in the context of `.flag`
I need to be able to dynamically create <select> element and turn it into jQuery .combobox(). This should be element creation event, as opposed to some "click" event in which case I could just use jQuery .on().
So does something like this exist?
$(document).on("create", "select", function() {
$(this).combobox();
}
I'm reluctant to use livequery, because it's very outdated.
UPDATE The mentioned select/combobox is loaded via ajax into a jQuery colorbox (modal window), thus the problem - I can only initiate combobox using colorbox onComplete, however on change of one combobox another select/combobox must be dynamically created, therefor I need a more generic way to detect creation of an element (selectin this case).
UPDATE2 To try and explain the problem further - I have select/combobox elements created recursively, there is also a lot of initiating code inside .combobox(), therefore if I used a classic approach, like in #bipen's answer, my code would inflate to insane levels. Hope this explains the problem better.
UPDATE3 Thanks everyone, I now understand that since deprecation of DOMNodeInserted there is a void left in DOM mutation and there is no solution to this problem. I'll just have to rethink my application.
You can on the DOMNodeInserted event to get an event for when it's added to the document by your code.
$('body').on('DOMNodeInserted', 'select', function () {
//$(this).combobox();
});
$('<select>').appendTo('body');
$('<select>').appendTo('body');
Fiddled here: http://jsfiddle.net/Codesleuth/qLAB2/3/
EDIT: after reading around I just need to double check DOMNodeInserted won't cause problems across browsers. This question from 2010 suggests IE doesn't support the event, so test it if you can.
See here: [link] Warning! the DOMNodeInserted event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.
As mentioned in several other answers, mutation events have been deprecated, so you should use MutationObserver instead. Since nobody has given any details on that yet, here it goes...
Basic JavaScript API
The API for MutationObserver is fairly simple. It's not quite as simple as the mutation events, but it's still okay.
function callback(records) {
records.forEach(function (record) {
var list = record.addedNodes;
var i = list.length - 1;
for ( ; i > -1; i-- ) {
if (list[i].nodeName === 'SELECT') {
// Insert code here...
console.log(list[i]);
}
}
});
}
var observer = new MutationObserver(callback);
var targetNode = document.body;
observer.observe(targetNode, { childList: true, subtree: true });
<script>
// For testing
setTimeout(function() {
var $el = document.createElement('select');
document.body.appendChild($el);
}, 500);
</script>
Let's break that down.
var observer = new MutationObserver(callback);
This creates the observer. The observer isn't watching anything yet; this is just where the event listener gets attached.
observer.observe(targetNode, { childList: true, subtree: true });
This makes the observer start up. The first argument is the node that the observer will watch for changes on. The second argument is the options for what to watch for.
childList means I want to watch for child elements being added or removed.
subtree is a modifier that extends childList to watch for changes anywhere in this element's subtree (otherwise, it would just look at changes directly within targetNode).
The other two main options besides childList are attributes and characterData, which mean about what they sound like. You must use one of those three.
function callback(records) {
records.forEach(function (record) {
Things get a little tricky inside the callback. The callback receives an array of MutationRecords. Each MutationRecord can describe several changes of one type (childList, attributes, or characterData). Since I only told the observer to watch for childList, I won't bother checking the type.
var list = record.addedNodes;
Right here I grab a NodeList of all the child nodes that were added. This will be empty for all the records where nodes aren't added (and there may be many such records).
From there on, I loop through the added nodes and find any that are <select> elements.
Nothing really complex here.
jQuery
...but you asked for jQuery. Fine.
(function($) {
var observers = [];
$.event.special.domNodeInserted = {
setup: function setup(data, namespaces) {
var observer = new MutationObserver(checkObservers);
observers.push([this, observer, []]);
},
teardown: function teardown(namespaces) {
var obs = getObserverData(this);
obs[1].disconnect();
observers = $.grep(observers, function(item) {
return item !== obs;
});
},
remove: function remove(handleObj) {
var obs = getObserverData(this);
obs[2] = obs[2].filter(function(event) {
return event[0] !== handleObj.selector && event[1] !== handleObj.handler;
});
},
add: function add(handleObj) {
var obs = getObserverData(this);
var opts = $.extend({}, {
childList: true,
subtree: true
}, handleObj.data);
obs[1].observe(this, opts);
obs[2].push([handleObj.selector, handleObj.handler]);
}
};
function getObserverData(element) {
var $el = $(element);
return $.grep(observers, function(item) {
return $el.is(item[0]);
})[0];
}
function checkObservers(records, observer) {
var obs = $.grep(observers, function(item) {
return item[1] === observer;
})[0];
var triggers = obs[2];
var changes = [];
records.forEach(function(record) {
if (record.type === 'attributes') {
if (changes.indexOf(record.target) === -1) {
changes.push(record.target);
}
return;
}
$(record.addedNodes).toArray().forEach(function(el) {
if (changes.indexOf(el) === -1) {
changes.push(el);
}
})
});
triggers.forEach(function checkTrigger(item) {
changes.forEach(function(el) {
var $el = $(el);
if ($el.is(item[0])) {
$el.trigger('domNodeInserted');
}
});
});
}
})(jQuery);
This creates a new event called domNodeInserted, using the jQuery special events API. You can use it like so:
$(document).on("domNodeInserted", "select", function () {
$(this).combobox();
});
I would personally suggest looking for a class because some libraries will create select elements for testing purposes.
Naturally, you can also use .off("domNodeInserted", ...) or fine-tune the watching by passing in data like this:
$(document.body).on("domNodeInserted", "select.test", {
attributes: true,
subtree: false
}, function () {
$(this).combobox();
});
This would trigger checking for the appearance of a select.test element whenever attributes changed for elements directly inside the body.
You can see it live below or on jsFiddle.
(function($) {
$(document).on("domNodeInserted", "select", function() {
console.log(this);
//$(this).combobox();
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// For testing
setTimeout(function() {
var $el = document.createElement('select');
document.body.appendChild($el);
}, 500);
</script>
<script>
(function($) {
var observers = [];
$.event.special.domNodeInserted = {
setup: function setup(data, namespaces) {
var observer = new MutationObserver(checkObservers);
observers.push([this, observer, []]);
},
teardown: function teardown(namespaces) {
var obs = getObserverData(this);
obs[1].disconnect();
observers = $.grep(observers, function(item) {
return item !== obs;
});
},
remove: function remove(handleObj) {
var obs = getObserverData(this);
obs[2] = obs[2].filter(function(event) {
return event[0] !== handleObj.selector && event[1] !== handleObj.handler;
});
},
add: function add(handleObj) {
var obs = getObserverData(this);
var opts = $.extend({}, {
childList: true,
subtree: true
}, handleObj.data);
obs[1].observe(this, opts);
obs[2].push([handleObj.selector, handleObj.handler]);
}
};
function getObserverData(element) {
var $el = $(element);
return $.grep(observers, function(item) {
return $el.is(item[0]);
})[0];
}
function checkObservers(records, observer) {
var obs = $.grep(observers, function(item) {
return item[1] === observer;
})[0];
var triggers = obs[2];
var changes = [];
records.forEach(function(record) {
if (record.type === 'attributes') {
if (changes.indexOf(record.target) === -1) {
changes.push(record.target);
}
return;
}
$(record.addedNodes).toArray().forEach(function(el) {
if (changes.indexOf(el) === -1) {
changes.push(el);
}
})
});
triggers.forEach(function checkTrigger(item) {
changes.forEach(function(el) {
var $el = $(el);
if ($el.is(item[0])) {
$el.trigger('domNodeInserted');
}
});
});
}
})(jQuery);
</script>
Note
This jQuery code is a fairly basic implementation. It does not trigger in cases where modifications elsewhere make your selector valid.
For example, suppose your selector is .test select and the document already has a <select>. Adding the class test to <body> will make the selector valid, but because I only check record.target and record.addedNodes, the event would not fire. The change has to happen to the element you wish to select itself.
This could be avoided by querying for the selector whenever mutations happen. I chose not to do that to avoid causing duplicate events for elements that had already been handled. Properly dealing with adjacent or general sibling combinators would make things even trickier.
For a more comprehensive solution, see https://github.com/pie6k/jquery.initialize, as mentioned in Damien Ó Ceallaigh's answer. However, the author of that library has announced that the library is old and suggests that you shouldn't use jQuery for this.
You can use DOMNodeInserted mutation event (no need delegation):
$('body').on('DOMNodeInserted', function(e) {
var target = e.target; //inserted element;
});
EDIT: Mutation events are deprecated, use mutation observer instead
Just came up with this solution that seems to solve all my ajax problems.
For on ready events I now use this:
function loaded(selector, callback){
//trigger after page load.
$(function () {
callback($(selector));
});
//trigger after page update eg ajax event or jquery insert.
$(document).on('DOMNodeInserted', selector, function () {
callback($(this));
});
}
loaded('.foo', function(el){
//some action
el.css('background', 'black');
});
And for normal trigger events I now use this:
$(document).on('click', '.foo', function () {
//some action
$(this).css('background', 'pink');
});
There is a plugin, adampietrasiak/jquery.initialize, which is based on MutationObserver that achieves this simply.
$.initialize(".some-element", function() {
$(this).css("color", "blue");
});
This could be done with DOM4 MutationObservers but will only work in Firefox 14+/Chrome 18+ (for now).
However there is an "epic hack" (author's words not mine!) that works in all browsers that support CSS3 animations which are: IE10, Firefox 5+, Chrome 3+, Opera 12, Android 2.0+, Safari 4+. See the demo from the blog. The hack is to use a CSS3 animation event with a given name that is observed and acted upon in JavaScript.
One way, which seems reliable (though tested only in Firefox and Chrome) is to use JavaScript to listen for the animationend (or its camelCased, and prefixed, sibling animationEnd) event, and apply a short-lived (in the demo 0.01 second) animation to the element-type you plan to add. This, of course, is not an onCreate event, but approximates (in compliant browsers) an onInsertion type of event; the following is a proof-of-concept:
$(document).on('webkitAnimationEnd animationend MSAnimationEnd oanimationend', function(e){
var eTarget = e.target;
console.log(eTarget.tagName.toLowerCase() + ' added to ' + eTarget.parentNode.tagName.toLowerCase());
$(eTarget).draggable(); // or whatever other method you'd prefer
});
With the following HTML:
<div class="wrapper">
<button class="add">add a div element</button>
</div>
And (abbreviated, prefixed-versions-removed though present in the Fiddle, below) CSS:
/* vendor-prefixed alternatives removed for brevity */
#keyframes added {
0% {
color: #fff;
}
}
div {
color: #000;
/* vendor-prefixed properties removed for brevity */
animation: added 0.01s linear;
animation-iteration-count: 1;
}
JS Fiddle demo.
Obviously the CSS can be adjusted to suit the placement of the relevant elements, as well as the selector used in the jQuery (it should really be as close to the point of insertion as possible).
Documentation of the event-names:
Mozilla | animationend
Microsoft | MSAnimationEnd
Opera | oanimationend
Webkit | webkitAnimationEnd
W3C | animationend
References:
caniuse.com summary of compatibility of CSS Animations.
CSS AnimationEvent Interface (W3C).
JavaScript animationend vendor-support.
For me binding to the body does not work. Binding to the document using jQuery.bind() does.
$(document).bind('DOMNodeInserted',function(e){
var target = e.target;
});
instead of...
$(".class").click( function() {
// do something
});
You can write...
$('body').on('click', '.class', function() {
// do something
});
I Think it's worth mentioning that in some cases, this would work:
$( document ).ajaxComplete(function() {
// Do Stuff
});
create a <select> with id , append it to document.. and call .combobox
var dynamicScript='<select id="selectid"><option value="1">...</option>.....</select>'
$('body').append(dynamicScript); //append this to the place your wanted.
$('#selectid').combobox(); //get the id and add .combobox();
this should do the trick.. you can hide the select if you want and after .combobox show it..or else use find..
$(document).find('select').combobox() //though this is not good performancewise
if you are using angularjs you can write your own directive. I had the same problem whith bootstrapSwitch. I have to call
$("[name='my-checkbox']").bootstrapSwitch();
in javascript but my html input object was not created at that time. So I write an own directive and create the input element with
<input type="checkbox" checkbox-switch>
In the directive I compile the element to get access via javascript an execute the jquery command (like your .combobox() command). Very important is to remove the attribute. Otherwise this directive will call itself and you have build a loop
app.directive("checkboxSwitch", function($compile) {
return {
link: function($scope, element) {
var input = element[0];
input.removeAttribute("checkbox-switch");
var inputCompiled = $compile(input)($scope.$parent);
inputCompiled.bootstrapSwitch();
}
}
});