1552016988
Essentially I want to have a script execute when the contents of a DIV
change. Since the scripts are separate (content script in the Chrome extension & webpage script), I need a way simply observe changes in DOM state. I could set up polling but that seems sloppy.
#javascript #jquery #google-chrome
1552019944
Several years later, there is now officially a better solution. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver
(or as the vendor-prefixed WebKitMutationObserver
in old versions of Chrome):
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
This example listens for DOM changes on document
and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:
childList* Set to
true
if mutations to target’s children are to be observed.
childList* Set totrue
if mutations to target’s children are to be observed.
childList* Set totrue
if mutations to target’s children are to be observed.
childList* Set totrue
if mutations to target’s children are to be observed.
childList* Set totrue
if mutations to target’s children are to be observed.
childList* Set totrue
if mutations to target’s children are to be observed.
childList* Set totrue
if mutations to target’s children are to be observed.
1552020016
This answer is now deprecated. See the answer by apsillers.
Since this is for a Chrome extension, you might as well use the standard DOM event - DOMSubtreeModified
. See the support for this event across browsers. It has been supported in Chrome since 1.0.
$("#someDiv").bind("DOMSubtreeModified", function() {
alert("tree changed");
});
See a working example here.
1552020065
nother approach depending on how you are changing the div. If you are using JQuery to change a div’s contents with its html() method, you can extend that method and call a registration function each time you put html into a div.
(function( $, oldHtmlMethod ){
// Override the core html method in the jQuery object.
$.fn.html = function(){
// Execute the original HTML method using the
// augmented arguments collection.
var results = oldHtmlMethod.apply( this, arguments );
com.invisibility.elements.findAndRegisterElements(this);
return results;
};
})( jQuery, jQuery.fn.html );
We just intercept the calls to html(), call a registration function with this, which in the context refers to the target element getting new content, then we pass on the call to the original jquery.html() function. Remember to return the results of the original html() method, because JQuery expects it for method chaining.
For more info on method overriding and extension, check out http://www.bennadel.com/blog/2009-Using-Self-Executing-Function-Arguments-To-Override-Core-jQuery-Methods.htm, which is where I cribbed the closure function. Also check out the plugins tutorial at JQuery’s site
1552020092
In addition to the “raw” tools provided by [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver "MutationObserver")
API, there exist “convenience” libraries to work with DOM mutations.
Consider: MutationObserver represents each DOM change in terms of subtrees. So if you’re, for instance, waiting for a certain element to be inserted, it may be deep inside the children of mutations.mutation[i].addedNodes[j]
.
Another problem is when your own code, in reaction to mutations, changes DOM - you often want to filter it out.
A good convenience library that solves such problems is [mutation-summary](https://github.com/rafaelw/mutation-summary "mutation-summary")
(disclaimer: I’m not the author, just a satisfied user), which enables you to specify queries of what you’re interested in, and get exactly that.
Basic usage example from the docs:
var observer = new MutationSummary({
callback: updateWidgets,
queries: [{
element: '[data-widget]'
}]
});
function updateWidgets(summaries) {
var widgetSummary = summaries[0];
widgetSummary.added.forEach(buildNewWidget);
widgetSummary.removed.forEach(cleanupExistingWidget);
}
1552020129
Many sites use AJAX to add/show/change content dynamically. Sometimes it’s used instead of in-site navigation, so current URL is changed programmatically and content scripts aren’t automatically executed by browser in this case since the page isn’t fetched from remote server entirely.
pjax:end
on document
used by many pjax-based sites e.g. GitHub,message
on window
used by e.g. Google search in Chrome browser,spfdone
on document
used by Youtube,document.head.appendChild(document.createElement('script')).text = '(' +
function() {
// injected DOM script is not a content script anymore,
// it can modify objects and functions of the page
var _pushState = history.pushState;
history.pushState = function(state, title, url) {
_pushState.call(this, state, title, url);
window.dispatchEvent(new CustomEvent('state-changed', {detail: state}));
};
// repeat the above for replaceState too
} + ')(); this.remove();'; // remove the DOM script element
// And here content script listens to our DOM script custom events
window.addEventListener('state-changed', function(e) {
console.log('History state changed', e.detail, location.hash);
doSomething();
});
pjax:end
on document
used by many pjax-based sites e.g. GitHub,message
on window
used by e.g. Google search in Chrome browser,spfdone
on document
used by Youtube,window.addEventListener('hashchange', function(e) {
console.log('URL hash changed', e);
doSomething();
});
window.addEventListener('popstate', function(e) {
console.log('State changed', e);
doSomething();
});
pjax:end
on document
used by many pjax-based sites e.g. GitHub,message
on window
used by e.g. Google search in Chrome browser,spfdone
on document
used by Youtube,There are advanced API to work with navigation: webNavigation, webRequest, but we’ll use simple chrome.tabs.onUpdated event listener that sends a message to the content script:
pjax:end
on document
used by many pjax-based sites e.g. GitHub,message
on window
used by e.g. Google search in Chrome browser,spfdone
on document
used by Youtube,var rxLookfor = /^https?:\/\/(www\.)?google\.(com|\w\w(\.\w\w)?)\/.*?[?#&]q=/;
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (rxLookfor.test(changeInfo.url)) {
chrome.tabs.sendMessage(tabId, 'url-update');
}
});
pjax:end
on document
used by many pjax-based sites e.g. GitHub,message
on window
used by e.g. Google search in Chrome browser,spfdone
on document
used by Youtube,chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg === 'url-update') {
doSomething();
}
});
1602841440
jQuery has been the savior for so many new and coming Web Developers, including myself. If you wanted to learn Web Development back in the day, learning jQuery was an absolute given. This was mainly because jQuery took much of the cross-browser compatibility issues out and enabled developers to write code without having to worry about whether the features that they are implementing will work on all browsers.
But with improvements in browser standards and most of jQuery’s API’s integrated into JavaScript, jQuery has become a little redundant. Moreover, with native browser API’s it is so much easier to debug code, and being native, most of these API’s offer better performance than jQuery’s API’s. Besides, you will have one less library to add to your script imports. If you’re still not sold on parting with jQuery maybe this answer will help.
So, if you’re considering a move away from jQuery, I have compiled a list of common jQuery methods and API’s that people use, with their Vanilla JS alternatives (Vanilla JS is a fancy name for plain JavaScript code without the use of any libraries). Let’s dive in!
The bread and butter of jQuery is it’s amazing ability to query DOM elements. This is demonstrated below:
jQuery('div.home')
However, you can achieve the same thing with JavaScript using it **document.querySelector() **and document.querySelectorAll() methods. Below is their implementation.
#javascript #replace-jquery #jquery #jquery-vs-javascript #faisal-rashid
1552016988
Essentially I want to have a script execute when the contents of a DIV
change. Since the scripts are separate (content script in the Chrome extension & webpage script), I need a way simply observe changes in DOM state. I could set up polling but that seems sloppy.
#javascript #jquery #google-chrome
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1591329120
jQuery vs vanilla JavaScript codes, DOM and css selectors, form validation
#javascript #jquery #dom
1650410220
jQuery — New Wave JavaScript
To build jQuery, you need to have the latest Node.js/npm and git 1.7 or later. Earlier versions might work, but are not supported.
For Windows, you have to download and install git and Node.js.
macOS users should install Homebrew. Once Homebrew is installed, run brew install git
to install git, and brew install node
to install Node.js.
Linux/BSD users should use their appropriate package managers to install git and Node.js, or build from source if you swing that way. Easy-peasy.
First, clone the jQuery git repo.
Then, enter the jquery directory and run the build script:
cd jquery && npm run build
The built version of jQuery will be put in the dist/
subdirectory, along with the minified copy and associated map file.
If you want to create custom build or help with jQuery development, it would be better to install grunt command line interface as a global package:
npm install -g grunt-cli
Make sure you have grunt
installed by testing:
grunt -V
Now by running the grunt
command, in the jquery directory, you can build a full version of jQuery, just like with an npm run build
command:
grunt
There are many other tasks available for jQuery Core:
grunt -help
Special builds can be created that exclude subsets of jQuery functionality. This allows for smaller custom builds when the builder is certain that those parts of jQuery are not being used. For example, an app that only used JSONP for $.ajax()
and did not need to calculate offsets or positions of elements could exclude the offset and ajax/xhr modules.
Any module may be excluded except for core
, and selector
. To exclude a module, pass its path relative to the src
folder (without the .js
extension).
Some example modules that can be excluded are:
$.ajax()
, $.get()
, $.post()
, $.ajaxSetup()
, .load()
, transports, and ajax event shorthands such as .ajaxStart()
.<script>
AJAX transport only; used to retrieve scripts..css()
method. Also removes all modules depending on css (including effects, dimensions, and offset)..show()
, .hide()
and .toggle()
; can be excluded if you use classes or explicit .css()
calls to set the display
property. Also removes the effects module..width()
and .height()
methods, including inner-
and outer-
variations..animate()
method and its shorthands such as .slideUp()
or .hide("slow")
..on()
and .off()
methods and all event functionality..trigger()
and .triggerHandler()
methods..offset()
, .position()
, .offsetParent()
, .scrollLeft()
, and .scrollTop()
methods..wrap()
, .wrapAll()
, .wrapInner()
, and .unwrap()
methods.jQuery()
will simply be called immediately. However, jQuery(document).ready()
will not be a function and .on("ready", ...)
or similar will not be triggered.grunt custom:-deferred,-ajax,-effects,-core/ready
).The build process shows a message for each dependent module it excludes or includes.
AMD name
As an option, you can set the module name for jQuery's AMD definition. By default, it is set to "jquery", which plays nicely with plugins and third-party libraries, but there may be cases where you'd like to change this. Simply set the "amd"
option:
grunt custom --amd="custom-name"
Or, to define anonymously, set the name to an empty string.
grunt custom --amd=""
To create a custom build, first check out the version:
git pull; git checkout VERSION
Where VERSION is the version you want to customize. Then, make sure all Node dependencies are installed:
npm install
Create the custom build using the grunt custom
option, listing the modules to be excluded.
Exclude all ajax functionality:
grunt custom:-ajax
Excluding css removes modules depending on CSS: effects, offset, dimensions.
grunt custom:-css
Exclude a bunch of modules:
grunt custom:-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-offset,-wrap
There is also a special alias to generate a build with the same configuration as the official jQuery Slim build is generated:
grunt custom:slim
For questions or requests regarding custom builds, please start a thread on the Developing jQuery Core section of the forum. Due to the combinatorics and custom nature of these builds, they are not regularly tested in jQuery's unit test process.
Make sure you have the necessary dependencies:
npm install
Start grunt watch
or npm start
to auto-build jQuery as you work:
grunt watch
Run the unit tests with a local server that supports PHP. Ensure that you run the site from the root directory, not the "test" directory. No database is required. Pre-configured php local servers are available for Windows and Mac. Here are some options:
To copy the built jQuery files from /dist
to another directory:
grunt && grunt dist:/path/to/special/location/
With this example, the output files would be:
/path/to/special/location/jquery.js
/path/to/special/location/jquery.min.js
To add a permanent copy destination, create a file in dist/
called ".destination.json". Inside the file, paste and customize the following:
{
"/Absolute/path/to/other/destination": true
}
Additionally, both methods can be combined.
As the source code is handled by the Git version control system, it's useful to know some features used.
If you want to purge your working directory back to the status of upstream, the following commands can be used (remember everything you've worked on is gone after these):
git reset --hard upstream/main
git clean -fdx
For feature/topic branches, you should always use the --rebase
flag to git pull
, or if you are usually handling many temporary "to be in a github pull request" branches, run the following to automate this:
git config branch.autosetuprebase local
(see man git-config
for more information)
If you're getting merge conflicts when merging, instead of editing the conflicted files manually, you can use the feature git mergetool
. Even though the default tool xxdiff
looks awful/old, it's rather useful.
The following are some commands that can be used there:
Ctrl + Alt + M
- automerge as much as possibleb
- jump to next merge conflicts
- change the order of the conflicted linesu
- undo a mergeleft mouse button
- mark a block to be the winnermiddle mouse button
- mark a line to be the winnerCtrl + S
- saveCtrl + Q
- quitexpect( numAssertions );
stop();
start();
Note: QUnit's eventual addition of an argument to stop/start is ignored in this test suite so that start and stop can be passed as callbacks without worrying about their parameters.
ok( value, [message] );
equal( actual, expected, [message] );
notEqual( actual, expected, [message] );
deepEqual( actual, expected, [message] );
notDeepEqual( actual, expected, [message] );
strictEqual( actual, expected, [message] );
notStrictEqual( actual, expected, [message] );
throws( block, [expected], [message] );
q( ... );
Example:
q("main", "foo", "bar");
=> [ div#main, span#foo, input#bar ]
t( testName, selector, [ "array", "of", "ids" ] );
Example:
t("Check for something", "//[a]", ["foo", "bar"]);
fireNative( node, eventType )
Example:
fireNative( jQuery("#elem")[0], "click" );
url( "some/url" );
Example:
url("index.html");
=> "data/index.html?10538358428943"
url("mock.php?foo=bar");
=> "data/mock.php?foo=bar&10538358345554"
Some tests may require a document other than the standard test fixture, and these can be run in a separate iframe. The actual test code and assertions remain in jQuery's main test files; only the minimal test fixture markup and setup code should be placed in the iframe file.
testIframe( testName, fileName,
function testCallback(
assert, jQuery, window, document,
[ additional args ] ) {
...
} );
This loads a page, constructing a url with fileName "./data/" + fileName
. The iframed page determines when the callback occurs in the test by including the "/test/data/iframeTest.js" script and calling startIframeTest( [ additional args ] )
when appropriate. Often this will be after either document ready or window.onload
fires.
The testCallback
receives the QUnit assert
object created by testIframe
for this test, followed by the global jQuery
, window
, and document
from the iframe. If the iframe code passes any arguments to startIframeTest
, they follow the document
argument.
In the spirit of open source software development, jQuery always encourages community code contribution. To help you get started and before you jump into writing code, be sure to read these important contribution guidelines thoroughly:
GitHub issues/PRs are usually referenced via gh-NUMBER
, where NUMBER
is the numerical ID of the issue/PR. You can find such an issue/PR under https://github.com/jquery/jquery/issues/NUMBER
.
jQuery has used a different bug tracker - based on Trac - in the past, available under bugs.jquery.com. It is being kept in read only mode so that referring to past discussions is possible. When jQuery source references one of those issues, it uses the pattern trac-NUMBER
, where NUMBER
is the numerical ID of the issue. You can find such an issue under https://bugs.jquery.com/ticket/NUMBER
.
If you have any questions, please feel free to ask on the Developing jQuery Core forum or in #jquery on libera.
Author: jquery
Source Code: https://github.com/jquery/jquery
License: MIT License