Binding to content change in body with jQuery - javascript

I have a function from icomoon that runs when the window loads (see below).
I would like to change it so that the function gets called once when the document loads, and then if there are any subsequent changes to the body - eg: from js/ajax (and preferably then only on the changed part of the dom, so as not to loop through the entire document again and again). Any suggestions on what jquery on events I should use for this, and then to only check the changes once the first execution on the entire document has been completed? Needs to be Ie7+ compatible too.
Thanks much.
$( window ).load(function() {
function addIcon(el, entity) {
$(el).addClass("iconed");
var html = el.innerHTML;
el.innerHTML = '<span style="font-family: \'icomoon\'">' + entity + '</span>' + html;
}
var icons = {
.....
};
function iconify() {
var els = document.getElementsByTagName('*'),
i, attr, c, el;
for (i = 0; ; i += 1) {
el = els[i];
if(!el) {
break;
}
attr = el.getAttribute('data-icon');
if (attr) {
if (!$(el).hasClass("iconed")) {
addIcon(el, attr);
}
}
c = el.className;
c = c.match(/icon-[^\s'"]+/);
if (c && icons[c[0]]) {
if (!$(el).hasClass("iconed")) {
addIcon(el, icons[c[0]]);
}
}
}
}
iconify();
$('body').on("contentchanged", function() { //some event that triggers ONCE the document has fully loaded, and is triggered when the DOM changes..
iconify(); //would prefer if this function only checked the modified part of the DOM - rather than the entire DOM each time (except on the 1st execution - when window loaded.
});
});

You can fire custom events when the content of body is changed by ajax or any other function which you are aware of . And then bind a custom function to that event.
Let's say in
function addIcon(el, entity) {
$(el).addClass("iconed");
var html = el.innerHTML;
el.innerHTML = '<span style="font-family: \'icomoon\'">' + entity + '</span>' + html;
$(document).trigger('contentchanged');
}
And then you can write a custom function handling this event like:
$(document).on('contentchange','selector',function(){
//Your code goes here.
});
You can also refer for DOM mutation events

Related

Using JQuery on a window reference?

Can you use JQuery on a window reference? I have tried the following with no luck.
function GetDiPSWindow() {
var DiPSURL = "/DiPS/index";
var DiPSWindow = window.open("", "DiPS", "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=520,height=875");
if (DiPSWindow.location.href === "about:blank") {
DiPSWindow.location = DiPSURL;
}
return DiPSWindow;
}
function AddRecipient(field, nameId) {
// Get window
var win = GetDiPSWindow();
// Attempt 1
$(win.document).ready(function () {
var input = win.document.getElementById(field + "_Input");
input.value = nameId;
});
// Attempt 2
$(win).ready(function () {
var input = win.document.getElementById(field + "_Input");
input.value = nameId;
});
// Attempt 3
$(win).load(function () {
var input = win.document.getElementById(field + "_Input");
input.value = nameId;
});
}
Am I making a simple mistake?
EDIT For some reason, win.document.readyState is "complete". Not sure if that makes a difference.
I have also tried:
View contains:
<script>var CallbackFunction = function() {}; // Placeholder</script>
The method:
function AddRecipient(field, nameId) {
var DiPSURL = "/DiPS/index";
if (deliveryChannel === undefined) {
deliveryChannel = 0;
}
var DiPSWindow = GetDiPSWindow();
if (DiPSWindow.location.href === "about:blank") {
DiPSWindow.location = DiPSURL;
DiPSWindow.onload = function () { DiPSWindow.CallbackFunction = AddRecipient(field, nameId) }
} else {
var input = DiPSWindow.document.getElementById(field + "_Input");
input.value = input.value + nameId;
var event = new Event('change');
input.dispatchEvent(event);
}
}
The answer is.... kinda. it depends on what you are doing.
You can use jquery on the parent page to interact with a page within an iframe, however, anything that requires working with the iframe's document object may not work properly because jQuery keeps a reference of the document it was included on and uses it in various places, including when using document ready handlers. So, you can't bind to the document ready handler of the iframe, however you can bind other event handlers, and you can listen for the iframe's load event to know when it is absolutely safe to interact with it's document.
It would be easier though to just include jquery within the iframe itself and use it instead. It should be cached anyway, so there's no real detriment to performance by doing so.

how to make the jquery function load before one ajax function finish

How do I fire one event before the previous function completed its function?
I have the following AJAX code :
var BrainyFilter = {
//...
init: function (opts) {},
changeTotalNumbers: function (data) {
jQuery(BrainyFilter.filterFormId).find('.bf-count').remove();
jQuery(BrainyFilter.filterFormId).find('option span').remove();
jQuery(BrainyFilter.filterFormId).find('select').removeAttr('disabled');
jQuery('.bf-attr-filter').not('#bf-price-container').find('input, option')
.attr('disabled', 'disabled')
.parents('.bf-attr-filter')
.addClass('bf-disabled');
if (data && data.length) {
for (var i = 0; i < data.length; i++) {
jQuery('.bf-attr-' + data[i].id + ' .bf-attr-val').each(function (ii, v) {
if (jQuery(v).text() == data[i].val) {
var parent = jQuery(v).parents('.bf-attr-filter').eq(0);
var isOption = jQuery(v).prop('tagName') == 'OPTION';
var selected = false;
if (isOption) {
jQuery(v).removeAttr('disabled');
selected = jQuery(v)[0].selected;
} else {
parent.find('input').removeAttr('disabled');
selected = parent.find('input')[0].checked;
}
parent.removeClass('bf-disabled');
if (!selected) {
if (!isOption) {
parent.find('.bf-cell').last().append('<span class="bf-count">' + data[i].c + '</span>');
} else {
jQuery(v).append('<span> (' + data[i].c + ')</span>');
}
}
}
});
}
jQuery('.bf-attr-filter input[type=checkbox]').filter(':checked')
.parents('.bf-attr-block').find('.bf-count').each(function (i, v) {
var t = '+' + jQuery(v).text();
jQuery(v).text(t);
});
// since opencart standard filters use logical OR, all the filter groups
// should have '+' if any filter was selected
if (jQuery('.bf-opencart-filters input[type=checkbox]:checked').size()) {
jQuery('.bf-opencart-filters .bf-count').each(function (i, v) {
var t = '+' + jQuery(v).text().replace('+', '');
jQuery(v).text(t);
});
}
}
// disable select box if it hasn't any active option
jQuery(BrainyFilter.filterFormId).find('select').each(function (i, v) {
if (jQuery(v).find('option').not('.bf-default,[disabled]').size() == 0) {
jQuery(v).attr('disabled', 'true');
}
});
},
//...
} // close the BrainyFilter
I also have another jQuery file running to get the bf-count value using $('.bf-count').text().
When the page load, the bf-count value is empty. Since the code above inject the bf-count, I will need to wait until it finishes the for loop in order to get the bf-count value.
What is the best way to approach this?
without knowing how the second js file is loaded, I can only give you a guesstimate suggestion.
If you want to run the second js file code after the page is fully loaded, you can wrap the code in:
jQuery(window).load(function(){
//your code here. runs after the page is fully loaded
});
jQuery documentation: http://api.jquery.com/load-event/
"The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object."

jQuery .change() event is only fired once

I have an application that retrieves Project names from a database when the DOM is ready. Each Project is added to a <select><option> in an html <form>. Once the list is populated the user can select a project title, which will request the remaining information from the database specific to that project.
To achieve this I'm using the $.change() jQuery method. Unfortunately, the event is only fired once when the <select> element is created and added to the DOM. Selecting another project from the list does not fire the event, and therefore does not trigger a $.post() call.
$(function(){
getProjects();
var firstLoad = true;
$("select").change(retrieveProject); // Removed parenthesis based on answers
// On page load, get project names from the database and add them to a Select form element
function getProjects() {
var selectionList;
$.getJSON("php/getProjects.php", function (data) {
selectionList = "<form><select>";
for (var i = 0; i < data.length; i++) {
selectionList += "<option name='prjTitle'>" + data[i].ProjectTitle + "</option>";
}
selectionList += "</select></form>";
}).complete(function() {
$('#project-selection-menu').append(selectionList).removeClass('hidden');
firstLoad = false;
});
}
function retrieveProject() {
if ( firstLoad == true ){
alert(firstLoad); // This alert fires
return false;
} else {
alert(firstLoad); // This alert doesn't fire
$.post("php/getProjects.php", function (data) { // This should have been "php/retrieveProject.php"!
// Do stuff with the returned data
}).complete(function() {
console.log("Success.");
});
}
}
)};
You're not setting up the event handler properly:
$("select").change(retrieveProject);
In your code, you were calling the "retrieveProject" function, and the return value from that function call was being passed as the "change" handler (and of course having no effect). That's why it appeared that the event was being generated upon page load.
When you're working with a function as a value, you don't use () after the function reference — it's the reference itself (the function name, in this case) that you want. That's what needs to be passed to jQuery.
Also — and this is important — make sure that your code is run either in a "ready" or "load" handler, or else that your <script> comes after the <select> element on the page. If the script is in the document head, then it'll run before the DOM is parsed, and it'll have no effect. (Another way to deal with that would be to use an .on() delegated form as suggested in another answer.)
More: it looks like you're overwriting your <select> element when you fetch the content in "getProjects". Thus, you should definitely use the delegated form:
$(document).on("change", "select", retrieveProject);
Also, you should be using local variables in "getProjects":
function getProjects() {
var selectionList; // keep this local to the function - implicit globals are risky
$.getJSON("php/getProjects.php", function (data) {
selectionList = "<form><select>";
for (var i = 0; i < data.length; i++) {
selectionList += "<option name='prjTitle'>" + data[i].ProjectTitle + "</option>";
}
selectionList += "</select></form>";
}).complete(function() {
$('#project-selection-menu').append(selectionList).removeClass('hidden');
firstLoad = false;
});
}
You need to handle event delegation
$(document).on('change', 'select', retrieveProject);
Also remove () next to the method retrieveProject
you can also do this by using following which will work fine.
$("select").change(function(){retrieveProject()});
or
$("select").on('change',function(){retrieveProject()});
Is this what your looking for? To run getProjects once the page loads just call it in your $(document).ready() function. Also you need to properly setup your change handler. See the fiddle for reference.
var firstLoad = true;
getProjects();
$("#selectTest").change(function(){
retrieveProject();
});
// On page load, get project names from the database and add them to a Select form element
function getProjects() {
$.getJSON("php/getProjects.php", function (data) {
selectionList = "<form><select>";
for (var i = 0; i < data.length; i++) {
selectionList += "<option name='prjTitle'>" + data[i].ProjectTitle + "</option>";
}
selectionList += "</select></form>";
}).complete(function() {
$('#project-selection-menu').append(selectionList).removeClass('hidden');
firstLoad = false;
});
}
function retrieveProject() {
if ( firstLoad == true ){
alert(firstLoad); // This alert fires
return false;
} else {
alert(firstLoad); // This alert doesn't fire
$.post("php/getProjects.php", function (data) {
// Do stuff with the returned data
}).complete(function() {
console.log("Success.");
});
}
}
http://jsfiddle.net/trevordowdle/Mf38E/
Try this:
$(document).bind('change', 'select', function(){
retrieveProject();
});

Dynamically add EventListener in JavaScript

I am populating a table with an XML file, I have a column that links to more details. Because of the way I'm running the web page (Chrome extension) I need to dynamically add an event handler when the table is populated.
I have this working...
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("detailLink").addEventListener('click',
clickHandlerDetailLink); });
function clickHandlerDetailLink(e) { detailLinkPress('SHOW'); }
function detailLinkPress(str) {
alert("Message that will show more detail");
}
But how do I go about adding the event handler dynamically? I have assigned all the fields in that column the id of detailLink.
You probably need to listen for a mutation event for the table, and then check each time the target element which has fired the event. Previously it used to be these events "DOMNodeInserted", or "DOMSubtreeModified", but they were very slow so according to new specifications the listener is called MutationObserver (which is much faster than the previous ones). This is an example from some Mozilla webpage edited for my testing :
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
alert(mutation.target.id + ", " + mutation.type +
(mutation.addedNodes ? ", added nodes(" + mutation.addedNodes.length + "): " + printNodeList(mutation.addedNodes) : "") +
(mutation.removedNodes ? ", removed nodes(" + mutation.removedNodes.length + "): " + printNodeList(mutation.removedNodes) : ""));
});
});
// configuration of the observer:
var config = { attributes: false, childList: true, characterData: false };
var element = document.getElementById('TestID');
// pass in the target node, as well as the observer options
observer.observe(element, config);
function printNodeList(nodelist)
{
if(!nodelist)
return "";
var i = 0;
var str = "";
for(; i < nodelist.length; ++i)
str += nodelist[i].textContent + ",";
return str;
}
If you want to assign an event to an element that doesn't yet exist, or to a series of elements (without creating one for each element), you need a delegate. A delegate is simply a parent element that will listen for the event instead of all the children. When it handles the event, you check to see if the element that threw the event is the one you're looking for.
If the parent <table> always exits, that would be a good place to add the listener. You can also add it to body. Also, you shouldn't be using detailLink as an id for more than one element. Use class instead.
Demo:
Script:
document.body.addEventListener( 'click', function ( event ) {
if( event.srcElement.className == 'detailLink' ) {
detailLinkPress( 'SHOW' );
};
} );
function detailLinkPress( str ) {
alert("Message that will show more detail");
};
HTML:
<div class="detailLink">click me</div>

Do something on :target with javascript

I'm using the CSS3 :target pseudo selector to create in-page navigation without reloading the page. This works really well!
But I have a problem, I need to reset the forms in a page when the page targetted, how can I know if an element is targetted with javascript? Like element.ontarget = function();
Or maybe something like element.ondisplaychange -> element.oncsschange?
BETTER UPDATE:
var hashcache = document.location.hash;
window.onhashchange = function() {
if(hashcache != document.location.hash) {
$(hashcache + ' form input').each(function() {
$(this).val('');
});
hashcache = document.location.hash;
}
}
UPDATE:
$('a[href^="#"]').each(function() {
this.onclick = function() {
href = $(this).attr('href');
if(href != document.location.hash) {
$(href + ' form input').each(function() {
$(this).val('');
});
}
}
});
If you're using JavaScript for the navigation, I'd suggest just adding the check to that. But I'm guessing from your question you're not, that you're instead using plain links with just anchors (e.g., <a href='#target1'>, <a href='#target2'>, ...).
A couple of options:
Use a Timer
In that case, basically what you want to do boils down to receiving an event when the anchor changes. As far as I know, and as far as the people answering this other question on StackOverflow in January knew, you can only do that with a timer. (Edit: But see ide's comment below, there's a new hashchange event we'll be able to use soon!) E.g.:
(function() {
var lastHash = window.location.hash;
setTimeout(function() {
var newHash = window.location.hash;
if (newHash !== lastHash) {
lastHash = newHash;
// Trigger your target change stuff
}
}, 250);
})();
That checks for changes every quarter second. That may not be enough for you, you could lower the 250, but beware running too much and slowing everything else down.
But as you say below, this is inefficient.
Hook the Link's click event
Since you're already using JavaScript on the page, I'd recommend using handlers on your links instead. If you add a class name or something to them (I bet they already have one; I'll us "navlink" below), this is easily set up:
var links, index, link;
links = document.getElementsByTagName('a');
for (index = 0; index < links.length; ++index) {
link = links.item(index);
if ((" " + link.className + " ").indexOf(" navlink ") >= 0) {
hookEvent(link, 'click', clickHandler);
}
}
function clickHandler() {
// `this` will reference the element that was clicked
}
// The 'hook' function:
var hookEvent = (function() {
var elm = document.createElement('a');
function hookEventViaAttach(element, event, handler) {
element.attachEvent("on" + event, handler);
}
function hookEventViaAddListener(element, event, handler) {
element.addEventListener(event, handler, false);
}
function hookEventDOM0(element, event, handler) {
element["on" + event.toLowerCase()] = handler;
}
if (elm.attachEvent) {
return hookEventViaAttach;
}
if (elm.addEventListener) {
return hookEventViaAddListener;
}
// I usually throw a failure here saying not supported, but if you want,
// you can use the DOM0-style stuff.
return hookEventDOM0;
})();
A lot of the complication of the above goes away if you use a library like jQuery, Prototype, YUI, Closure, or any of several others.
For instance, the jQuery version:
$("a.navlink").click(clickHandler);
function clickHandler() {
// `this` will reference the element that was clicked
}
The Prototype version:
$$("a.navlink").invoke('observe', 'click', clickHandler);
function clickHandler() {
// `this` will reference the element that was clicked
}
The onfocus property returns the onFocus event handler code on the current element.
event handling code = element.onfocus
The onblur property returns the onBlur event handler code, if any, that exists on the current element.
element.onblur = function;
Example: http://jsfiddle.net/g105b/cGHF7/
<html>
<head>
<title>onblur event example</title>
<script type="text/javascript">
var elem = null;
function initElement()
{
elem = document.getElementById("foo");
// NOTE: doEvent(); or doEvent(param); will NOT work here.
// Must be a reference to a function name, not a function call.
elem.onblur = doEvent;
};
function doEvent()
{
elem.value = 'Bye-Bye';
alert("onblur Event detected!")
}
</script>
<style type="text/css">
<!--
#foo {
border: solid blue 2px;
}
-->
</style>
</head>
<body onload="initElement()";>
<form>
<input type="text" id="foo" value="Hello!" />
</form>
<p>Click on the above element to give it focus, then click outside the
element.<br /> Reload the page from the NavBar.</p>
</body>
</html>
Maybe youcan just code like this
function hashChangeEvent(){
$(window.location.hash)//do something
}
window.onhashchange = hashChangeEvent;//when hash change
hashChangeEvent();//first load

Categories

Resources