• Stars
    star
    133
  • Rank 272,600 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A jQuery plug-in to watch CSS style and attribute changes and get notified when a change occurs

jquery-watch

A jQuery plug-in to notify you of CSS, Attribute or Property changes in an element

This small jQuery plug-in allows you to monitor changes to any DOM element's CSS styles, attributes or properties and fires a callback in response to any change in the monitored styles or attributes.

You can specify an element and any number of CSS properties attribute or property names you want to monitor and if any of them are changed you are notified of the change via a function delegate you provide. The function delegate receives an object with an array of property names and current values, plus an index for the one that triggered the change.

Related Resources

Installation

To install jquery-watch either copy the jquery-watch scripts out of the root folder of this repository, or use Bower or NPM to install it into your project:

$ Bower install jquery-watch-dom

Note the differing name (jquery-watch-dom rather than jquery-watch) for the Bower package due to a naming conflict with an existing bower package.

$ npm install jquery-watch 

Usage

To use the plugin add a reference to jQuery and a reference to this plugin to your page:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jquery-watch.min.js"></script>

To hook up an element for monitoring in script code use:

// some element to monitor
var el = $("#notebox");

// hook up the watcher
el.watch({
    // specify CSS styles or attribute names to monitor
    properties: "top,left,opacity,attr_class,prop_innerHTML",

    // callback function when a change is detected
    callback: function(data, i) {
		var propChanged = data.props[i];
        var newValue = data.vals[i];
	
		var el = this;
		var el$ = $(this);

        // do what you need based on changes
        // or do your own checks
	}
});

You simply specify the CSS styles or attributes to monitor and then hook up a call back function, and wait for change notifications to come in.

Note that you can get quite a lot of notifications especially if you're monitoring things like opacity during a fade operation or top/left during drag operations, so you should keep the code in this function to a minimum.

Watching Property and Content Changes

You can also monitor property changes by watching any direct properties that are associated with a given jQuery DOM element set.

For example assume you have a button that changes some text in a DOM element:

<button id="btnChangeContent">Change Content</button>
<div id="SomeContent">Some Content that can change.</div>

To capture the programmatic change you can now use the following code:

$("#btnChangeContent").click(function () {
    // assign text programmatically
    $("#SomeContent").text("Hello - time is " + new Date());
});
// watch the content
$("#SomeContent").watch({
    properties: "prop_innerHTML",
    watchChildren: true,
    callback: function (data, i) {
        console.log("text changed");
        alert('text changed' + data.vals[i]);
    }
});

Whenever you click the button and the text is changed an alert box pops up from the watcher notification.

Syntax

The syntax uses standard jQuery plug-in behavior attached to an element selector:

$("#Element").watch(options)

where options looks like this:

var options = {
    // CSS styles or Attributes to monitor as comma delimited list
    // For attributes use a attr_ prefix
    // Example: "top,left,opacity,attr_class,prop_innerHTML"
    properties: null,

    // interval for 'manual polling' (IE 10 and older)            
    interval: 100,

    // a unique id for this watcher instance
    id: "_watcher",

    // flag to determine whether child elements are watched            
    watchChildren: false,

    // Callback function if not passed in callback parameter   
    callback: null
}

The main required property to set is properties which can contain any CSS Style property (top, left, opacity, display etc.), an attribute name prefixed by attr_ (attr_class,attr_readonly,attr_src etc.) or a property name prefixed by prop_' (prop_innerHTML, prop_value etc). attr_andprop_` use jQuery's attr() and prop() functions respectively to check the relevant keys.

The other required property is the callback property which lets you specify a callback function called when one (or more) of the properties change. The callback function receives two parameters which is an instance of a data object that contains an array of the properties monitored and the latest values.

An implementation of the callback function looks like this:

function changeCallback(data, i) {
	// data object and index into the arrays
    var changedProperty = data.props[i];
    var newValue = data.vals[i];
    
    // this is the element affected
    var el$ = $(this)

    //... do your logic
}

If you only care to be notified and you don't care about changed or updated values, you can ignore the parameters - which is actually quite common. In that case you can do your own checks in your code to find what's changed or update other properties as needed.

If you want to know which element caused the event to fire you can use the code shown above to retrieve the changedProperty and newValue for property.

Note that the change event tracking is turned off for the duration of the callback function execution to avoid recursive events firing causing a potential browser lockup. If you need to make changes that require updating the DOM that affect further change events, you should use setTimeout() to delay execution until after the callback has completed.

Example Usage

As an example consider you have a couple of HTML elements - two boxes and you want to slave one box to the other:

<div class="container">
    <div id="notebox" class="notebox">
        <p>
            This is the master window. Go ahead drag me around and close me!
        </p>
        <p>
            The shadow window should follow me around and close/fade when I do.
        </p>
        <p>
            There's also a timer, that fires and alternates a CSS class every
            3 seconds.
        </p>
    </div>

    <div id="shadow" class="shadow">
        <p>I'm the Shadow Window!</p>
        <p>I'm shadowing the Master Window.</p>
        <p>I'm a copy cat</p>
        <p>I do as I'm told.</p>
    </div>
</div>

There are two boxes #notebox and #shadow and what we want to do is monitor changes on #notebox and affect the behavior of #shadow to keep #shadow tied and synched to the #notebox.

The following code monitors #notebox so we can tell when a monitored value is changed:

var el = $("#notebox");
el.draggable();

// Also update a CSS Class on a 3 sec timer
var state = false;
setInterval(function () {
    $("#notebox")
        .removeClass("class_true")
        .removeClass("class_false")
        .addClass("class_" + state);
    state = !state;
}, 3000);


// Hook up CSS and Class watch operation
el.watch({
    properties: "top,left,opacity,attr_class",
    callback: watchShadow
});

// this is the handler function that responds
// to the events. Passes in:
// data.props[], data.vals[] and an index for active item
function watchShadow(data, i) {
    // you can capture which attribute has changed
    var propChanged = data.props[i];
    var valChanged = data.vals[i];

    // element affected is 'this'
    var el = $(this);
    var sh = $("#shadow");

    // get master current position
    var pos = el.position();
    var w = el.outerWidth();
    var h = el.outerHeight();

    // and update shadow accordingly
    sh.css({
        width: w,
        height: h,
        left: pos.left + w + 4,
        top: pos.top,
        display: el.css("display"),
        opacity: el.css("opacity")
    });

    // Class attribute is more tricky since there are
    // multiple classes on the parent - we have to explicitly
    // check for class existance and assign
    sh.removeClass("class_true")
        .removeClass("class_false");
    if (el.hasClass("class_true"))
        sh.addClass("class_true");
}

When you run this code you'll essentially see #shadow follow around the #notebox when dragged or moved, fade out when the #notebox fades. You'd also see the CSS class of #shadow changed every three seconds, in response to the change on #notebox.

Note that the code above doesn't actually rely on the parameters passed into the watchShadow function, but instead does its own checks to see what needs updating. In fact this code simply updates all relevant properties whether they have changed or not. While less efficient it allows for simpler code and depending on how much change you need to do on the DOM, this can be very fast regardless. Your mileage may vary. If you have larger changes you need to affect, using the specific property to update the UI might be more appropriate.

Watching Child Elements

You can also monitor changes to child nodes by setting .watchChildren to true and then looking at the mutation record to figure out if nodes have been removed or added:

$list.watch({
        properties: 'prop_innerHTML',
        watchChildren: true,
        callback: function (data, i, mutations) {

            mutations.forEach(function(record) {
                if (record.type === 'childList' && record.removedNodes.length > 0) {
                    console.info('removed item');        
                } else if (record.addedNodes.length > 0) {
                    console.info('added item');
                }
            });
        }
    });

Browser Support

This plug-in will work with just about any browser, as it has a fallback for legacy browsers using interval polling. Modern browsers use an efficient API to get notified of changes by the browser.

This plug-in relies on the MutationObserver API in modern browsers to detect change events on elements. This API is supported in all current versions of Chrome, Mozilla, Safari, Safari iOS, and Internet Explorer 11.

Older versions of IE (10 and older) and any old browser that doesn't support MutationObserver can still work by using an inefficient setInterval() polling mechanism. It works, but there's always a slight, configurable delay between events being detected and the callback executing. However this fallback should work in any browser and so provides backwards compatibility. You can adjust the polling delay (default is 10ms), but you'll want to be careful to not poll too frequently to avoid slowing down browser operation especially on slower/older devices/machines.

License

Licensed under the MIT License. There's no charge to use, integrate or modify the code for this project. You are free to use it in personal, commercial, government and any other type of application.

All source code is copyright West Wind Technologies, regardless of changes made to them. Any source code modifications must leave the original copyright code headers intact.

Warranty Disclaimer: No Warranty!

IN NO EVENT SHALL THE AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THIS PROGRAM AND DOCUMENTATION, BE LIABLE FOR ANY COMMERCIAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR LOSSES SUSTAINED BY THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS, EVEN IF YOU OR OTHER PARTIES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

Change Log

Version 1.20

  • Add NPM Install
    You can now install jquery-watch from NPM in addition to bower using npm install jquery-watch

  • Allow for multiple watch handlers on a single DOM element Fixed behavior to allow multiple watchers on a single DOM element by assigning a unique ID to the stored state for the watcher. This means multiple calls to .watch() can be made and all of them will trace their own properties and fire their own events.

Version 1.16

  • Make default Watcher ID a unique ID
    Changed the default id assignment that the watcher attaches to a unique ID which allows for multiple watcher attachments to the same element by default. Previously it was your responsibility to create new unique Ids if multiple watchers are used. You can now receive multiple events firing when attaching watchers to the same element more than once.

Version 1.15

  • Bug Fix: Options parameter passing
    Fixed issue where the options.interval was not properly passed which caused problems for non-recent and IE-old browser that don't support MutationObservers.

  • Add support for Property watches with _prop Prefix
    You can now attach to property change values by prefixing a property name with prop_. So if you want to monitor a value change on an input box you can add prop_value or if you want to monitor the content of an element or container watch prop_innerHTML.

More Repositories

1

MarkdownMonster

An extensible Markdown Editor, Viewer and Weblog Publisher for Windows
HTML
1,584
star
2

Westwind.Globalization

Database driven resource localization for .NET applications
C#
543
star
3

AlbumViewerVNext

West Wind Album Viewer ASP.NET Core and Angular Sample
JavaScript
505
star
4

Westwind.AspnetCore.LiveReload

ASP.NET Core Live Reload Middleware that monitors file changes in your project and automatically reloads the browser's active page
C#
470
star
5

WestWindWebSurge

Quick and easy URL and Load Testing for your Web applications on Windows
388
star
6

WestwindToolkit

A utility toolkit for .NET development from Core to Web
C#
273
star
7

Westwind.Utilities

A general purpose utility and helper library for .NET development
C#
255
star
8

Westwind.AspNetCore.Markdown

An ASP.NET Core Markdown support library that provides Markdown parsing, a Markdown TagHelper and Markdown Page Handler Middleware
C#
248
star
9

jquery-resizable

A small jQuery plug-in to make DOM components resizable
PowerShell
234
star
10

Westwind.Scripting

Small C# library to provide dynamic runtime code compilation from source code for code and expressions execution
C#
205
star
11

Westwind.ApplicationConfiguration

Strongly typed, code-first configuration classes for .NET applications
C#
178
star
12

Westwind.RazorHosting

Hosting the Razor Runtime outside of ASP.NET/MVC for use in non-Web .NET applications.
C#
144
star
13

SetResolution

Quickly set Windows Display Resolution via Command Line
C#
128
star
14

Westwind.AspNetCore

ASP.NET Core Helpers and Utilities
C#
126
star
15

Expando

Extensible dynamic types for .NET
C#
108
star
16

LiveReloadServer

A self-contained, local, cross-platform, static file Web Server based on .NET with automatic Live Reloading, Markdown rendering and loose Razor Pages support.
CSS
100
star
17

json.date-extensions

Date parsing extensions for the JavaScript JSON parser to provide real dates from JSON.parse()
JavaScript
93
star
18

wwDotnetBridge

.NET Interop for Visual FoxPro made easy
C#
73
star
19

AspNetWebApiArticle

Source code for ASP.NET WebApi Article for Code Magazine
JavaScript
66
star
20

DeleteFiles

Windows Console Utility to delete files and folders recursively with optional date filtering
C#
62
star
21

CodePaste.NET

CodePaste.NET site code
JavaScript
58
star
22

highlightjs-badge

Addon component to highlightjs that lets you copy code snippets to the clipboard and displays the active syntax
CSS
46
star
23

HtmlSanitizer

A base Html Sanitizer for .NET
C#
35
star
24

Westwind.HtmlPackager

A small utility class used to package HTML content into a self contained HTML document both as a single file, or a folder with all dependencies copied to local.
C#
35
star
25

AspNetFrameworksPerformance

ASP.NET Raw Throughput Performance Post Sample
C#
31
star
26

AspNetCoreRawRequestSample

Sample code for Accepting Raw Request Body in Asp.NET Core Applications
C#
31
star
27

CordovaAlbumViewer

Sample code for "Taming Mobile Apps with Cordova and Visual Studio" CODE magazine article
JavaScript
30
star
28

Westwind.plUploadHandler

An ASP.NET base HttpHandler library to handle plUpload content on the server.
JavaScript
28
star
29

wwMongoDb

Access MongoDb from Visual FoxPro
xBase
25
star
30

WestWind.WebView.HtmlToPdf

Creating Pdf output from Html with .NET on Windows using the WebView2 control
HTML
25
star
31

Westwind.Wpf.Statusbar

A small WPF library to provide animated status bar operations
C#
24
star
32

VisualStudioSnippetConverter

Utility to convert Visual Studio Code Snippets to VS Code and Rider.
C#
22
star
33

vue-mover

A 2 list mover component implemented as a VueJs Component
JavaScript
19
star
34

Westwind.Web.Markdown

Markdown support for ASP.NET WebForms and MVC applications
C#
19
star
35

DotnetDesktopRuntimeInstaller

A tiny Windows console executable that can be distributed with an application and called from an installer to download and install the .NET runtime.
C#
18
star
36

GistIntegration-MarkdownMonster-Addin

Markdown Monster addin to create embeddable Gists for Markdown documents, and to load and save documents from Gists.
C#
17
star
37

Westwind.QueueMessageManager

.NET Library to provide a simple, two-way messaging queue for enabling offloading of long running operations to other processes/machines.
JavaScript
16
star
38

Westwind.WebView

A .NET support library for the `Microsoft.Web.WebView2` control to aid with common operations and .NET / JavaScript interop.
HTML
14
star
39

AspNetCoreFromScratchSample

Working example to experiment with building Asp.net core from scratch
C#
14
star
40

SignalrChatSample

Sample SignalR Chat application that demonstrates VueJs, Angular, FoxPro and .NET clients to SignalR
JavaScript
12
star
41

Westwind.AspNetCore.HostedWebServer

Sample that demonstrates how to create a minmal ASP.NET Web Server that can be hosted in a desktop (or other non-Web) application easily.
C#
12
star
42

Westwind.Data.EfCore

Lightweight Business Object wrapper for Entity framework that handles CRUD operations and error handling.
C#
12
star
43

BlogPosts

HTML
11
star
44

MarkdownMonsterAddinsRegistry

Markdown Monster Addin Registry
10
star
45

Pandoc-MarkdownMonster-Addin

A Pandoc Markdown Parser and Pandoc Operations Library for Markdown Monster
C#
10
star
46

Commander-MarkdownMonster-Addin

Commander C# Scripting Addin that can be used to automate simple tasks in Markdown Monster without creating an Addin. Launch external tools, update documents or mail merge content into the editor.
C#
10
star
47

WpfWebView2Playground

JavaScript
9
star
48

DI2017-AspNet-Core-Angular

Session Materials for Dev Intersection ASP.NET Core and Angular Session
TypeScript
9
star
49

CodeMagazine-DotnetTools

Code Magazine Article Materials for Dotnet Tools Article
C#
8
star
50

VirtualFoxFest2021-FoxProRest

JavaScript
8
star
51

SaveToAzureBlob-MarkdownMonster-Addin

Markdown Monster Addin to open or paste images from your local machine and save them in Azure Blob Storage and embed link into your post.
C#
8
star
52

anti-trust-guilty-album

Anti-Trust Guilty Album - Punk Rock Music
JavaScript
7
star
53

Westwind.Webstore

West Wind Web Store Sample application
JavaScript
7
star
54

HelpBuilderReleases

West Wind Html Help Builder Releases and Bug Reporting
6
star
55

MarkdownMonsterReleases

6
star
56

Snippets-MarkdownMonster-Addin

A Snippet Expansion Manager for embedding templated text into Markdown Monster Markdown documents
C#
6
star
57

West-Wind-Message-Board

West Wind Message Board Web Connection (FoxPro) Sample Application
JavaScript
6
star
58

AspetCoreIISInprocessHostingSample

Simple test project optimized for Hello World style controller ops for comparison of hosting options on Windows
C#
5
star
59

DI2017-ASP.NET-Core-Localization

Session materials for DevIntersection 2017 - ASP.NET Core Localization
JavaScript
5
star
60

Padnug-2016-Angular-AspNet

Sample application and Slides from Rick's May 2nd, 2016 Angular ASP.NET Core Presentation
TypeScript
5
star
61

Console-MarkdownMonster-Addin

A simple Console/Terminal addin for Markdown Monster that displays a terminal window attached to the main Markdown Monster Window
C#
5
star
62

Westwind.Ai

Sample project that demonstrates OpenAI Image Generation
C#
5
star
63

datepicker-native

JavaScript and Vue helper components to make it easier to bind dates to the input/date control and a date button picker.
JavaScript
5
star
64

Westwind.AI

C#
4
star
65

Blazor_Playground

Blazor Sample Application
C#
4
star
66

WestwindWebSurgeReleases

Repository that holds releases for West Wind WebSurge
4
star
67

GithubRespositoryParser

C# Github Repository and Content Retrieval Examples using regular and GraphQL APIs.
C#
3
star
68

MarkdownMonsterAddinProjectTemplate

A Visual Studio Project Template for creating a Markdown Monster Addin
C#
3
star
69

Base64

C#
3
star
70

QfxToQboConverter

A small utility to fix up Quicken QIF files (.qfx) so they can be opened as QBO in Quickbooks.
C#
3
star
71

VirtualFoxFest2022-FoxProDotnet

Session Notes and Samples for Virtual FoxFest FoxPro .NET Interop Session
xBase
3
star
72

Live-Writer-SnagIt-Screen-Capture-Plugin

A Live Writer plug-in to provide screen capturing using TechSmith's SnagIt
C#
3
star
73

SWFOX2019_Vue

JavaScript
3
star
74

SWFOX18_WebConnectionSecurity

2
star
75

samples.west-wind.com

West Wind Samples Web Site
HTML
2
star
76

ChromiumPreview-MarkdownMonster-Addin

A Chromium Preview Browser Addin for the Markdown Monster Markdown Editor
C#
2
star
77

Westwind.Weblog

Source for Westwind Weblog
C#
2
star
78

KavaDocs-MarkdownMonster-Addin

KavaDocs Integration for Markdown Monster
C#
2
star
79

EmptyWebContentProjectTemplate

Empty Content Web Site Project that publishes from the root folder and works optionally with WebDeploy
HTML
2
star
80

SWFOX2019_DotnetCore

JavaScript
2
star
81

CODE.Framework.Core.ServiceHandler

C#
1
star
82

MarkdownMonsterDocumentation

JavaScript
1
star
83

swfox2024-wwdotnetbridge-revisited

Samples, Session Notes and Slides for Southwest Fox 2024 Sessions
HTML
1
star
84

dotnet-tools-padnug2020

1
star
85

WebSurgeDocumentation

Documentation for West Wind WebSurge
JavaScript
1
star
86

WebConnection-WebDemo

Web Connection Sample Application for the Getting Started Walk Through
JavaScript
1
star
87

HighPerformanceAspNet

C#
1
star
88

SWFOX2019_WebConnectionDeployment

PowerShell
1
star
89

SWFOX2018_MarkdownWithFoxPro

JavaScript
1
star