jQuery livequery plug equivalent in jQuery 1.7+ - html

Is there the equivalent of the jQuery livequery plugin for jQuery 1.7+ ?
I'm trying to dynamically bind events, reading the events a DOM element should bind on based on data-* elements.
Test 1
Test 2
.. etc ..
I want to bind all elements with class .js-test but only on the events listed in their data-events attribute.
jQuery.on/live/bind/delegate all require the events to be passed in as params.
This is find for DOM elements that exist on the page when document.ready, however as I update the DOM (AJAX, JS, etc.) I want any new elements with class .js-test to have its events bound as well.
The livequery plugin (which is old, from jQuery 1.3 times) seems to allow this, as it simple requires a selector and a function to run against anything that matches the selector.

As of jQuery 1.7 the on method, supercedes the live method. While it doesn't have an easy method of passing in or matching selectors like you describe, it is possible to accomplish this by passing in the dynamic value of data-events in place of the event type, as long as the data-event value matches that event.
However, since the argument passed into the on method's event parameter -- the first parameter -- is taken from each data-events attribute, from each element in the set of matched elements, we must loop through the collection of matched elements so that we access each elements' individual data-events attribute value separately:
$('.js-test').each(function() {
$(this).on( $(this).attr("data-events"), function() {
// event pulled from data-events attribute
alert("hello - this event was triggered by the " + $(this).attr("data-events") + " action.");
});
});
I want all events to be mapped to the same function, but have different events trigger the function call for different DOM elements.
Since you want to map all of the events to a single function, this solution meets your specific requirements, and solves your problem.
However, should your requirements change and you find you need to map a collection of function events to match each event type, this should get you started:
var eventFnArray = [];
eventFnArray["click"] = function() {
alert("click event fired - do xyz here");
// do xyz
};
eventFnArray["mouseover"] = function() {
alert("mouseover fired - do abc here");
// do abc
};
$('.js-test').each( (function(fn) {
return function() {
$(this).on( $(this).attr("data-events"), function() {
alert("hello - this is the " + $(this).attr("data-events") + " event");
// delegate to the correct event handler based on the event type
fn[ $(this).attr("data-events") ]();
});
}
})(eventFnArray)); // pass function array into closure
UPDATE:
This has been tested and does indeed work for new elements added to the div#container. The problem was in the way the on method functions. The delegating nature of on only works if the parent element is included in the selector, and only if a selector is passed into the second parameter, which filters the target elements by data-events attribute:
HTML:
<div id="container">
Test 1
Test 2
</div>
JavaScript:
$(document).ready(function() {
$('.js-test').each(function() {
var _that = this;
alert($(_that).attr("data-events"));
$(this).parent().on(
$(_that).attr("data-events"),
'.js-test[data-events="'+ $(_that).attr("data-events") +'"]',
function() {
// event pulled from data-events attribute
alert("hello - this event was triggered by the " + $(_that).attr("data-events") + " action.");
}
);
}
);
});
Additionally, use the following jQuery to add an item to the container to test it:
$('#container')
.append("<a href='#' class='js-test' data-events='mouseover'>Test 3</a>");
Try it out:
Here is a jsfiddle that demonstrates the tested and working functionality.

Related

getting the value of a code-mirror element

I am using the code-mirror component from the Polymer Designer, and can set the initial value, but cannot see how to get changes to the code from the user.
I initialise the code-mirror using
<code-mirror id="code_mirror" value="{{code}}">
</code-mirror>
and would like to listen for changes in {{code}}, but codeChanged doesn't seem to fire.
I know I can get the actual value using code_mirror.$.mirror.getValue(), but would like to use data-binding.
I have tried using on-change to no avail.
Assuming you're using https://github.com/PolymerLabs/code-mirror what you need to do is make the CodeMirror instance created in the ready handle some events that the instance itself is emitting, then make the code-mirror element fire any custom event (something which I know is called event relay)
The following example makes the polymer element fire the custom event code-change whenever the editor value is changed
ready: function() {
var me = this;
//...
this.mirror = CodeMirror(this.shadowRoot, { /* ... */ });
this.mirror.on('change', function () {
// me = polymer instance
me.fire('code-change', { value: me.mirror.getValue() })
});
}
Then any instance of the polymer custom element would need to listen to that event using Polymer's declarative event mapping or through addEventListener
1st case (if code-mirror is inside another <polymer-element />):
<code-mirror on-code-change="{{ onCodeChange }}"></code-mirror>
// ...
<script>
Polymer({
onCodeChange: function(event, detail, sender) { ... }
});
</script>
2nd case ():
<code-mirror></code-mirror>
<script>
document
.querySelector('code-mirror')
.addEventListener('code-change', function () { ... });
</script>

Adding properties for a Polymer element to observe based on content or a better way to handle forms

I need to create a form using the Polymer Paper-Input elements, and I need a way to know when all required content has been filled out.
I looked for a built in element, but didn't see one. So I wanted to create a polymer form element that would wrap all of the input tags. The resulting element would have an Invalid attribute which lets you know if any of the input tags are invalid.
The use of the tag would look like this:
<test-form id="testform">
<paper-input label="test" required error="This field is required"></paper-input>
</test-form>
Invalid: {{ $.testform.invalid }}
However, it appears that by the time in the elements lifecycle that I can loop over all the elements inside of the content tag, that anything added to the observe object is ignored.
Here is the code I was working on below:
<polymer-element name="test-form" attributes="invalid">
<template>
<content id="content">
</content>
</template>
<script>
Polymer('test-form', {
domReady: function () {
this.observe = {};
for (var i = 0; i < this.children.length; i++) {
this.observe["this.children[" + i + "].invalid"] = "valChanged";
}
},
invalid: false,
valChanged: function (oldValue, newValue) {
// TODO: If newValue is true set invalid to true
// If newValue is false, loop over all elements to see if all are now valid and invalid can be set to false.
alert("VALUE CHANGED" + oldValue + newValue);
}
});
</script>
Is there a better way to handle this or does anyone know how to make changes to what polymer is observing at this point in the lifecycle?
As far as checking the form's validity, you could simply check each form element's invalid property:
validate: function() {
var invalid = false;
Array.prototype.forEach.call(this.children, function(child) {
if (child.invalid === true) {
invalid = true;
}
});
this.invalid = invalid;
}
Then you could add an input event listener and run this method each time a form element's input changes.
Here's a working jsbin.
If I understand your question, your high level goal is form validation?
As has been detailed in polycasts and other places, I have used iron-form which has some very powerful validate() functionality, including what you mention above and much more.
It does sometimes require some odd usages of hidden <input> fields to get all of the work done, but this is easy to learn in the polycasts, such as polycast 55 and 56
If you stumbled upon this question in 2017, you would definitely now want to use more primitive tech, after you've seen what this has to offer.

Transverse Html Elements Till a Specifc Attribute (id) using Jquery

I am using Jquery 1.7.2.
I want to transverse Html Elements Till a Specifc Attribute (id) using Jquery on
mouse over on any html element in my page.
we have parents() function but problem is how to select stop on the parent element which has id attribute
$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
var parentEls = $(domEl).parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
$("b").append("" + parentEls + "");
});
this is code but i am getting all element till root
but i want to stop on a closet elements which has attribute id in the tag
Please help me out .
Just use closest:
$(this).closest('#the-id');
Unless your'e just looking for the closest one that has any id attribute, which would be:
$(this).closest('[id]');
Edit: after seeing your updated question, this should be what you want:
$(document).click(function(e) {
e.preventDefault();
var parents = $(e.target).parentsUntil('[id]')
.map(function() { return this.tagName; }).get().join(',');
console.log(parents);
});
Note that this approach accomplishes what you want without selecting and binding click events to every node in the DOM, which is a pretty heavy handed approach.
Edit (again): looks like maybe you wanted to include the tag with the id attribute on it (the above solution is everything up to, but not including that tag). To do this, the solution is pretty similar:
$(document).click(function(e) {
e.preventDefault();
var $parents = $(e.target).parentsUntil('[id]');
var tagNames = $parents.add($parents.parent())
.map(function() { return this.tagName; }).get().join(',');
console.log(tagNames);
});
It looks like you want to map the hierarchy from the clicked element up to the document root. In that case, you can apply parents() to event.target:
$(document).click(function(e) {
e.preventDefault();
var parentEls = $(e.target).parents().map(function() {
return this.tagName;
}).get().join(", ");
});
Note that, as jmar777, you should also change your selector: "*" adds an event handler to all the elements, which is probably not what you want. Bind a single handler to document instead to take advantage of event bubbling.

How to do callback + update div tag in javascript

I have an ASP.NET MVC application with pages where the content is loaded into divs from client via JavaScript/jQuery/JSON. The loaded content contains a-tags with references to a function that updates server side values, then redirects to reload of entire page even though.
I wish to replace the a-tags with 'something' to still call a server-side function, then reload the div only.
What is the 'right' way of doing this?
All comments welcome.
This is as far as I got so far. getResponseCell() returns a td-tag filled with a-tag.
I've mangled Glens suggestion into the .click() addition, but it just calls the onClickedEvent...
Code sample:
onClickedEvent=function()
{
return false;
}
getResponseCell=function(label, action, eventId)
{
tmpSubSubCell=document.createElement("td");
link = document.createElement("A");
link.appendChild( document.createTextNode( label));
link.setAttribute("href", "/EventResponse/"+ action + "/" + eventId);
//link.setAttribute("href", "#divContentsEventList");
//link.setAttribute("onclick", "onClickedEvent(); return false;");
link.setAttribute("className", "eventResponseLink");
link.click(onClickedEvent());
// link=jQuery("<A>Kommer<A/>").attr("href", "/EventResponse/"+ action + "/" + eventId).addClass("eventResponseLink");
// link.appendTo(tmpSubSubCell);
tmpSubSubCell.appendChild(link);
return tmpSubSubCell;
}
And the solution that worked for me looks like this:
onClickedEvent=function(event, actionLink)
{
event.preventDefault();
$("eventListDisplay").load(actionLink);
refreshEventList();
return false;
}
getResponseCell=function(label, action, eventId)
{
tmpSubSubCell=document.createElement("td");
link = document.createElement("A");
link.setAttribute("id",action + eventId);
link.appendChild( document.createTextNode( label));
actionLink = "/EventResponse/"+ action + "/" + eventId;
link.setAttribute("href", actionLink);
className = "eventResponseLink"+ action + eventId;
link.setAttribute("className", className);
$('a.'+className).live('click', function (event)
{
onClickedEvent(event,$(this).attr('href'));
});
tmpSubSubCell.appendChild(link);
return tmpSubSubCell;
}
Without really seeing more information.....
If you're a's are being added to the DOM after the initial page load, you cannot use the usual click() or bind() methods in jQuery; this is because these methods only bind the events to those elements that are registered in the DOM at the time the methods are called. live() on the other hand, will register the event for all current, and future elements (using the event bubbling mechanism in Javascript).
$(document).ready(function () {
$('a.eventResponseLink').live('click', function (event) {
var self = $(this);
self.closest('div').load('/callYourServerSideFunction.asp?clickedHref=' + self.attr('href'));
event.preventDefault();
});
});
We're using event.preventDefault() to prevent the default action of the a-tag being executed; e.g. reloading or changing page.
Edit: The issue won't be caused by that. That's the power of jQuery; being able to bind the same event to multiple elements. Check your HTML; maybe you're missing a closing </a> somewhere? Maybe your binding the event in a location that gets called multiple times? Each time .live() gets called, it will add ANOTHER event handler to all matched elements. It only needs to be bound once on page load.
jQuery provides loads of way for you to select the elements; check out the list. Looking at your link variable, it looks like all your links have a href starting with /EventResponse/; so you can use $('a[href^=/EventResponse/]') as the selector instead.
We need code to give you a proper answer, but the following code will catch the click of an a-tag, and reload the div that it's inside:
$(document).ready(function() {
$("a").click(function() {
//call server-side function
var parentDiv = $(this).parents("div:first");
$(parentDiv).load("getContentOfThisDiv.asp?id=" + $(parentDiv).attr("id"));
});
});
In the above code, when a link is clicked, the div that this the link is inside will be loaded with the response of the call to the asp file. The id of the div is sent to the file as a parameter.

mootools 1.11 div contains checked checkbox

how can mootools 1.11 determine if a div contains any checked check boxes?
tried all kinds of variations using $ $$ $E $ES getElements and css selectors, its just not returning true if this div contains no tick boxes
var ticked = $(sId).getElements('[checked=checked]');
if($chk(ticked)){alert('yo');}else{unticked = true;}
"checked" is a dynamically assigned DOM property (which is a boolean), and accessing the attribute only returns the value that was there when the page loaded (or the value you placed when using setAttribute).
Also, as MooTools 1.11 does not have complex selectors (attributes can not be filtered directly within $$) and the filterByAttribute function only accepts direct string comparison, this is your only (and best!) option:
$(sId).getElements('input').filter(function(input) {
return /radio|checkbox/.test(input.getAttribute('type')) && input.checked;
})
note: I added radio just for completeness, the filter loop would have to be run anyways to verify the checked status.
If you want to simplify the process and be able to reuse the code (the MooTools way), you can also mix-in the checked filter into Elements like this:
Element.extend({
getCheckedInputs: function() {
return this.getElements('input').filter(function(input) {
return /radio|checkbox/.test(input.getAttribute('type')) && input.checked;
});
}
});
and then your selection call is reduced to:
$(sID).getCheckedInputs();
From The Documentation:
$(sId).getElements("input:checked");
for 1.1
console.log( $('id').getProperty('checked') );