Giter Site home page Giter Site logo

fabiospampinato / cash Goto Github PK

View Code? Open in Web Editor NEW
6.4K 88.0 262.0 2.46 MB

An absurdly small jQuery alternative for modern browsers.

License: MIT License

JavaScript 59.30% HTML 0.66% TypeScript 39.64% Shell 0.40%
cash selector modern-browsers javascript dom jquery-alternative typescript tiny small jquery

cash's Introduction

Cash Logo

Cash

Cash is an absurdly small jQuery alternative for modern browsers (IE11+) that provides jQuery-style syntax for manipulating the DOM. Utilizing modern browser features to minimize the codebase, developers can use the familiar chainable methods at a fraction of the file size. 100% feature parity with jQuery isn't a goal, but Cash comes helpfully close, covering most day to day use cases.

Comparison

Size Cash Zepto 1.2.0 jQuery Slim 3.4.1
Unminified 36.5 KB 58.7 KB 227 KB
Minified 16 KB 26 KB 71 KB
Minified & Gzipped 6 KB 9.8 KB 24.4 KB

A 76.6% gain in size reduction compared to jQuery Slim. If you need a smaller bundle, we support partial builds too.

Features Cash Zepto 1.2.0 jQuery Slim 3.4.1
Supports Older Browsers ️❌
Supports Modern Browsers ️✔
Actively Maintained
Namespaced Events ️❌
Typed Codebase ✔ (TypeScript) ️❌
TypeScript Types ✔ (generated from code) ⚠️ (via DefinitelyTyped) ⚠️ (via DefinitelyTyped)
Partial Builds ✔ (can exclude individual methods) ⚠️ (can exclude whole modules) ⚠️ (can exclude whole modules)

If you're migrating from jQuery be sure to read our migration guide.

Usage

You can get Cash from jsDelivr and use it like this:

<script src="https://cdn.jsdelivr.net/npm/cash-dom/dist/cash.min.js"></script>
<script>
  $(function () {
    $('html').addClass ( 'dom-loaded' );
    $('<footer>Appended with Cash</footer>').appendTo ( document.body );
  });
</script>

Cash is also available through npm as the cash-dom package:

npm install --save cash-dom

That you can then use like this:

import $ from "cash-dom";

$(function () {
  $('html').addClass ( 'dom-loaded' );
  $('<footer>Appended with Cash</footer>').appendTo ( document.body );
});

Documentation

Cash gives you a query selector, collection methods and some library methods. If you need more details about our API just check out jQuery's, while we don't implement everything that jQuery provides, pretty much everything that we do implement should be compatible with jQuery. Cash can be extended with custom methods, read how here.

$()

This is the main selector method for Cash. It returns an actionable collection of nodes.

If a function is provided, the function will be run once the DOM is ready.

$( selector [, element] ) // => collection, using `element` as the context
$( selector [, collection] ) // => collection, using `collection` as the context
$(node) // => collection
$(nodeList) // => collection
$(htmlString) // => collection
$(collection) // => self
$(function () {}) // => document ready callback

Collection Methods

These methods from the collection prototype ($.fn) are available once you create a collection with $() and are called like so:

$(element).addClass ( className ) // => collection

Some extra methods are available but disabled by default.

Attributes Collection CSS Data Dimensions Effects
fn.addClass () fn.add () fn.css () fn.data () fn.height () fn.hide ()
fn.attr () fn.each () fn.innerHeight () fn.show ()
fn.hasClass () fn.eq () fn.innerWidth () fn.toggle ()
fn.prop () fn.filter () fn.outerHeight ()
fn.removeAttr () fn.first () fn.outerWidth ()
fn.removeClass () fn.get () fn.width ()
fn.removeProp () fn.index ()
fn.toggleClass () fn.last ()
fn.map ()
fn.slice ()
Events Forms Manipulation Offset Traversal
fn.off () fn.serialize () fn.after () fn.offset () fn.children ()
fn.on () fn.val () fn.append () fn.offsetParent () fn.closest ()
fn.one () fn.appendTo () fn.position () fn.contents ()
fn.ready () fn.before () fn.find ()
fn.trigger () fn.clone () fn.has ()
fn.detach () fn.is ()
fn.empty () fn.next ()
fn.html () fn.nextAll ()
fn.insertAfter () fn.nextUntil ()
fn.insertBefore () fn.not ()
fn.prepend () fn.parent ()
fn.prependTo () fn.parents ()
fn.remove () fn.parentsUntil ()
fn.replaceAll () fn.prev ()
fn.replaceWith () fn.prevAll ()
fn.text () fn.prevUntil ()
fn.unwrap () fn.siblings ()
fn.wrap ()
fn.wrapAll ()
fn.wrapInner ()

$.fn

The main prototype for collections, allowing you to extend Cash with plugins by adding methods to all collections.

$.fn // => Cash.prototype
$.fn.myMethod = function () {}; // Custom method added to all collections
$.fn.extend ( object ); // Add multiple methods to the prototype

fn.add ()

Returns a new collection with the element(s) added to the end.

$(element).add ( element ) // => collection
$(element).add ( selector ) // => collection
$(element).add ( collection ) // => collection

fn.addClass ()

Adds the className class to each element in the collection.

Accepts space-separated className for adding multiple classes.

$(element).addClass ( className ) // => collection

fn.after ()

Inserts content or elements after the collection.

$(element).after ( element ) // => collection
$(element).after ( htmlString ) // => collection
$(element).after ( content [, content] ) // => collection

fn.append ()

Appends content or elements to each element in the collection.

$(element).append ( element ) // => collection
$(element).append ( htmlString ) // => collection
$(element).append ( content [, content] ) // => collection

fn.appendTo ()

Adds the elements in the collection to the target element(s).

$(element).appendTo ( element ) // => collection

fn.attr ()

Without attrValue, returns the attribute value of the first element in the collection.

With attrValue, sets the attribute value of each element of the collection.

$(element).attr ( attrName ) // value
$(element).attr ( attrName, attrValue ) // => collection
$(element).attr ( object ) // => collection

fn.before ()

Inserts content or elements before the collection.

$(element).before ( element ) // => collection
$(element).before ( htmlString ) // => collection
$(element).before ( content [, content] ) // => collection

fn.children ()

Without a selector specified, returns a collection of child elements.

With a selector, returns child elements that match the selector.

$(element).children () // => collection
$(element).children ( selector ) // => collection

fn.closest ()

Returns the closest matching selector up the DOM tree.

$(element).closest ( selector ) // => collection

fn.contents ()

Get the children of each element in the set of matched elements, including text and comment nodes.

Useful for selecting elements in friendly iframes.

$('iframe').contents ().find ( '*' ) // => collection

fn.clone ()

Returns a collection with cloned elements.

$(element).clone () // => collection

fn.detach ()

Removes collection elements, optionally that match the selector, from the DOM.

$(element).detach () // => collection
$(element).detach ( selector ) // => collection

fn.css ()

Returns a CSS property value when just property is supplied.

Sets a CSS property when property and value are supplied.

Sets multiple properties when an object is supplied.

Properties will be autoprefixed if needed for the user's browser.

$(element).css ( property ) // => value
$(element).css ( property, value ) // => collection
$(element).css ( object ) // => collection

fn.data ()

Without arguments, returns an object mapping all the data-* attributes to their values.

With a key, return the value of the corresponding data-* attribute.

With both a key and value, sets the value of the corresponding data-* attribute to value.

Multiple data can be set when an object is supplied.

$(element).data () // => object
$(element).data ( key ) // => value
$(element).data ( key, value ) // => collection
$(element).data ( object ) // => collection

fn.each ()

Iterates over a collection with callback ( index, element ). The callback function may exit iteration early by returning false.

$(element).each ( callback ) // => collection

fn.empty ()

Empties the elements interior markup.

$(element).empty () // => collection

fn.eq ()

Returns a collection with the element at index.

$(element).eq ( index ) // => collection

fn.extend ()

Adds properties to the Cash collection prototype.

$.fn.extend ( object ) // => object

fn.filter ()

Returns the collection that results from applying the filter selector/method.

$(element).filter ( selector ) // => collection
$(element).filter ( function ( index, element ) {} ) // => collection

fn.find ()

Returns selector match descendants from the first element in the collection.

$(element).find ( selector ) // => collection

fn.first ()

Returns a collection containing only the first element.

$(element).first () // => collection

fn.get ()

Returns the element at the index, or returns all elements.

$(element).get ( index ) // => domNode
$(element).get () // => domNode[]

fn.has ()

Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

$(element).has ( selector ) // => collection
$(element).has ( element ) // => collection

fn.hasClass ()

Returns the boolean result of checking if any element in the collection has the className attribute.

$(element).hasClass ( className ) // => boolean

fn.height ()

Returns or sets the height of the element.

$(element).height () // => Integer
$(element).height ( number ) // => collection

fn.hide ()

Hide the elements.

$(element).hide () // => collection

fn.html ()

Returns the HTML text of the first element in the collection, sets the HTML if provided.

$(element).html () // => HTML Text
$(element).html ( htmlString ) // => HTML Text

fn.index ()

Returns the index of the element in its parent if an element or selector isn't provided. Returns index within element or selector if it is.

$(element).index () // => Integer
$(element).index ( element ) // => Integer

fn.innerHeight ()

Returns the height of the element + padding.

$(element).innerHeight () // => Integer

fn.innerWidth ()

Returns the width of the element + padding.

$(element).innerWidth () // => Integer

fn.insertAfter ()

Inserts collection after specified element.

$(element).insertAfter ( element ) // => collection

fn.insertBefore ()

Inserts collection before specified element.

$(element).insertBefore ( element ) // => collection

fn.is ()

Returns whether the provided selector, element or collection matches any element in the collection.

$(element).is ( selector ) // => boolean

fn.last ()

Returns a collection containing only the last element.

$(element).last () // => collection

fn.map ()

Returns a new collection, mapping each element with callback ( index, element ).

$(selector).map ( callback ) // => collection

fn.next ()

Returns the next adjacent elements.

$(element).next () // => collection
$(element).next ( selector ) // => collection

fn.nextAll ()

Returns all the next elements.

$(element).nextAll () // => collection
$(element).nextAll ( selector ) // => collection

fn.nextUntil ()

Returns all the next elements, until the provided selector matches.

$(element).nextUntil ( selector ) // => collection
$(element).nextUntil ( selector, filterSelector ) // => collection

fn.not ()

Filters collection by false match on collection/selector.

$(element).not ( selector ) // => collection
$(element).not ( collection ) // => collection

fn.off ()

Removes event listener from collection elements.

Accepts space-separated eventName for removing multiple events listeners.

Removes all event listeners if called without arguments.

$(element).off ( eventName, eventHandler ) // => collection
$(element).off ( eventName ) // => collection
$(element).off ( eventsMap ) // => collection
$(element).off () // => collection

fn.offset ()

Get the coordinates of the first element in a collection relative to the document.

$(element).offset () // => Object

fn.offsetParent ()

Get the first element's ancestor that's positioned.

$(element).offsetParent () // => collection

fn.on ()

Adds event listener to collection elements.

Accepts space-separated eventName for listening to multiple events.

Event is delegated if delegate is supplied.

$(element).on ( eventsMap ) // => collection
$(element).on ( eventName, eventHandler ) // => collection
$(element).on ( eventName, delegate, eventHandler ) // => collection

fn.one ()

Adds event listener to collection elements that only triggers once for each element.

Accepts space-separated eventName for listening to multiple events.

Event is delegated if delegate is supplied.

$(element).one ( eventName, eventHandler ) // => collection
$(element).one ( eventName, delegate, eventHandler ) // => collection

fn.outerHeight ()

Returns the outer height of the element. Includes margins if includeMargings is set to true.

$(element).outerHeight () // => Integer
$(element).outerHeight ( includeMargins ) // => Integer

fn.outerWidth ()

Returns the outer width of the element. Includes margins if includeMargings is set to true.

$(element).outerWidth () // => Integer
$(element).outerWidth ( includeMargins ) // => Integer

fn.parent ()

Returns collection of elements who are parent of elements.

$(element).parent () // => collection
$(element).parent ( selector ) // => collection

fn.parents ()

Returns collection of elements who are parents of elements. Optionally filtering by selector.

$(element).parents () // => collection
$(element).parents ( selector ) // => collection

fn.parentsUntil ()

Returns collection of elements who are parents of elements, until a provided selector matches. Optionally filtering by selector.

$(element).parentsUntil ( selector ) // => collection
$(element).parentsUntil ( selector, filterSelector ) // => collection

fn.position ()

Get the coordinates of the first element in a collection relative to its offsetParent.

$(element).position () // => object

fn.prepend ()

Prepends content or elements to the each element in collection.

$(element).prepend ( element ) // => collection
$(element).prepend ( htmlString ) // => collection
$(element).prepend ( content [, content] ) // => collection

fn.prependTo ()

Prepends elements in a collection to the target element(s).

$(element).prependTo ( element ) // => collection

fn.prev ()

Returns the previous adjacent elements.

$(element).prev () // => collection
$(element).prev ( selector ) // => collection

fn.prevAll ()

Returns all the previous elements.

$(element).prevAll () // => collection
$(element).prevAll ( selector ) // => collection

fn.prevUntil ()

Returns all the previous elements, until the provided selector matches.

$(element).prevUntil ( selector ) // => collection
$(element).prevUntil ( selector, filterSelector ) // => collection

fn.prop ()

Returns a property value when just property is supplied.

Sets a property when property and value are supplied, and sets multiple properties when an object is supplied.

$(element).prop ( property ) // => property value
$(element).prop ( property, value ) // => collection
$(element).prop ( object ) // => collection

fn.ready ()

Calls callback method on DOMContentLoaded.

$(document).ready ( callback ) // => collection/span

fn.remove ()

Removes collection elements, optionally that match the selector, from the DOM and removes all their event listeners.

$(element).remove () // => collection
$(element).remove ( selector ) // => collection

fn.replaceAll ()

This is similar to fn.replaceWith (), but with the source and target reversed.

$(element).replaceAll ( content ) // => collection

fn.replaceWith ()

Replace collection elements with the provided new content.

$(element).replaceWith ( content ) // => collection

fn.removeAttr ()

Removes attribute from collection elements.

Accepts space-separated attrName for removing multiple attributes.

$(element).removeAttr ( attrName ) // => collection

fn.removeClass ()

Removes className from collection elements.

Accepts space-separated className for adding multiple classes.

Providing no arguments will remove all classes.

$(element).removeClass () // => collection
$(element).removeClass ( className ) // => collection

fn.removeProp ()

Removes property from collection elements.

$(element).removeProp ( propName ) // => collection

fn.serialize ()

When called on a form, serializes and returns form data.

$(form).serialize () // => String

fn.show ()

Show the elements.

$(element).show () // => collection

fn.siblings ()

Returns a collection of sibling elements.

$(element).siblings () // => collection
$(element).siblings ( selector ) // => collection

fn.slice ()

Returns a new collection with elements taken from start to end.

$(selector).slice ( start, end ) // => collection

fn.text ()

Returns the inner text of the first element in the collection, sets the text if textContent is provided.

$(element).text () // => text
$(element).text ( textContent ) // => collection

fn.toggle ()

Hide or show the elements.

$(element).toggle () // => collection
$(element).toggle ( force ) // => collection

fn.toggleClass ()

Adds or removes className from collection elements based on if the element already has the class.

Accepts space-separated classNames for toggling multiple classes, and an optional force boolean to ensure classes are added (true) or removed (false).

$(element).toggleClass ( className ) // => collection
$(element).toggleClass ( className, force ) // => collection

fn.trigger ()

Triggers supplied event on elements in collection. Data can be passed along as the second parameter.

$(element).trigger ( eventName ) // => collection
$(element).trigger ( eventObj ) // => collection
$(element).trigger ( eventName, data ) // => collection
$(element).trigger ( eventObj, data ) // => collection

fn.unwrap ()

Removes the wrapper from all elements.

$(element).unwrap () // => collection

fn.val ()

Returns an inputs value. If value is supplied, sets all inputs in collection's value to the value argument.

$(input).val () // => value
$(input).val ( value ) // => collection

fn.width ()

Returns or sets the width of the element.

$(element).width () // => number
$(element).width ( number ) // => collection

fn.wrap ()

Wraps a structure around each element.

$(element).wrap ( structure ) // => collection

fn.wrapAll ()

Wraps a structure around all elements.

$(element).wrapAll ( structure ) // => collection

fn.wrapInner ()

Wraps a structure around all children.

$(element).wrapInner ( structure ) // => collection

Cash Methods

These methods are exported from the global $ object, and are called like so:

$.isArray ( arr ) // => boolean

Some extra methods are available but disabled by default.

Type Checking Utilities
$.isArray () $.guid
$.isFunction () $.each ()
$.isNumeric () $.extend ()
$.isPlainObject () $.parseHTML ()
$.isWindow () $.unique ()

$.guid

A unique number.

$.guid++ // => number

$.each ()

Iterates through an array and calls the callback ( index, element ) method on each element.

Iterates through an object and calls the callback ( key, value ) method on each property.

The callback function may exit iteration early by returning false.

$.each ( array, callback ) // => array
$.each ( object, callback ) // => object

$.extend ()

Extends target object with properties from the source object, potentially deeply too.

$.extend ( target, source ) // => object
$.extend ( true, target, source ) // => object

$.isArray ()

Check if the argument is an array.

$.isArray ([ 1, 2, 3 ]) // => true

$.isFunction ()

Check if the argument is a function.

function fn () {};
$.isFunction ( fn ) // => true

$.isNumeric ()

Check if the argument is numeric.

$.isNumeric ( 57 ) // => true

$.isPlainObject ()

Check if the argument is a plain object.

$.isPlainObject ( {} ) // => true

$.isWindow ()

Check if the argument is a Window object.

$.isWindow ( window ) // => true

$.parseHTML ()

Returns a collection from an HTML string.

$.parseHTML ( htmlString ) // => collection

$.unique ()

Returns a new array with duplicates removed.

$.unique ( array ) // => array

Contributing

If you found a problem, or have a feature request, please open an issue about it.

If you want to make a pull request you should:

  1. Clone the repository: git clone https://github.com/fabiospampinato/cash.git.
  2. Enter the cloned repository: cd cash
  3. Install the dependencies: npm install.
  4. Automatically recompile Cash whenever a change is made: npm run dev.
  5. Open the test suite: npm run test.
  6. Remember to update the readme, if necessary.

Thanks

License

MIT © Fabio Spampinato

cash's People

Contributors

arthurvr avatar augustmiller avatar bdadam avatar danielruf avatar defrag avatar devinargenta avatar digitaljhelms avatar dkuku avatar fabiospampinato avatar fransreijnhoudt avatar gabrielcramer avatar imba-tjd avatar ipavlic avatar jamiebuilds avatar joezimjs avatar kenwheeler avatar kornalius avatar limonte avatar lukasdrgon avatar michael-mader avatar mienaikoe avatar peachicetea avatar richguan avatar shshaw avatar shvelo avatar simeydotme avatar softwarespot avatar tjbenton avatar vivekimsit avatar vovayatsyuk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cash's Issues

Cannot set property length of #<HTMLCollection> which has only a getter

Error: Uncaught TypeError: Cannot set property length of # which has only a getter(…)
OS: OSX El Capitan
Browser: Chrome 49

First: Thank you!
Having an issue when trying to interact with the DOM in the latest version of Chrome. See attached screenshot. Seems to be the case both when and individual node is selected or it has an array and across multiple functions.

Quick glance shows it coming from here:

cash.extend = fn.extend = function (target, source) {
    var prop;

    if (!source) {
      source = target;
      target = this;
    }

    for (prop in source) {
      if (source.hasOwnProperty(prop)) {
        target[prop] = source[prop];
      }
    }

    return target;
  };

screen shot 2016-03-10 at 6 35 12 pm

attr(obj) similar to css(obj)

The attr method only supports attr(key) and attr(key, val) syntax, but it would be helpful to also support attr(obj) syntax similar to the css method.

Implementing a sticky footer with Cash

I was previously using a sticky-footer plugin for jQuery, but the amount of jQuery specific API it uses is big... so, I would like to know how I could implement a sticky footer with Cash?

With sticky footer, I mean that the footer always stays on the bottom.

Migrate to Babel

Migrating from 6to5 to Babel for better ES6 conversion to fixing the global "use strict"; ( #49 ) and help future proof the code

Can't chain methods after append(), appendTo()

I noticed that after append and appendTo, the object returned is the plain dom object instead of the cash object. The result is that chaining methods results in "undefined is not a function".

I'll try to send a pull-request your way unless you have a specific way you want it done.

parent(), parents(), add().... and $.unique y'all...

Hey @kenwheeler ... while thinking of ways to make your life more difficult I came across this scenario 😜


The Scene

<section class="brangelina">
    <div class="baby"></div>
    <span class="baby"></span>
</section>
<a class="tom-cruise">
    <span class="baby"></span>
</a>
cash(".baby").parent();

Now, I looked at that and slapped myself!! 😵 Thinking

Why do celebrities love to adopt children didn't I consider this before when I wrote .parents()??

but then I realised that the answer was in the .add() method that you helped me to "dedupe".

Basically; we should be returning both the parent of the <div> and the <span>'s ... not just the first item... but more than that; in the scenario above, the first <span> and the <div> unfortunately share .brangelina as their parent, we do not need/want .brangelina to be in the returned collection two times; that's. just. silly.


Changes

  1. Create a utility method called $.unique to remove duplicates from a collection.
  2. Update .parent() and .parents() to return all parents of all items in collection.
  3. Profit. 💰

simeydotme/cash@kenwheeler:master...patch-parents-with-unique

Please take a look over my branch when you are able, and let me know what you think about the proposed changes? should I place a PR? 😄

Potentially if you like this pattern if can be applied to all the methods which deal with returning a collection from a prior collection?

Regards, Simon.

ajax implementation is too lightweight

A few things jQuery does and I really miss:

  1. Set the content-type myself: I often post JSON payloads to my server.
  2. Return the xhr object (or a wrapper): e.g. to be able to call .cancel() on it.
  3. Return a Promise, because programming async code with callbacks is hell when you do more than trivial stuff. This is also the way to go with modern browsers (await is proposed for ES7).

isArray Example incorrect.

###Currently
$.isArray()
Check if the argument is an array.
$.isString([1,2,3]) // => true
###Should be
$.isArray()
Check if the argument is an array.
$.isArray([1,2,3]) // => true

.parents() functionality

Hey, I hope I'm not wrong; but it seems like the .parents() method currently functions similarly to .closest() method in jQuery (but resorts to .parent() if no selector given), which is confusing because jQuery also has a .parents() which actually returns a representation of the DOM tree focused down to that element... optionally filtered by a selector.

I realise Cash isn't trying to be a clone of jQuery, however I personally think their naming/functionality here is logical and there's probably no reason to deviate from it. I did notice the readme/docu seems to indicate it was supposed to function the same as jQuery, and I hope you weren't already working on it, because I took the liberty to do it...

Please let me know what you think, and as I mention if you've already done this in upcoming release I'll just undo my commits... I learn't a few things again so I'm happy either way 😉

Do not use script-wide use strict statement

You are using a script-wide form of use strict statement. This may cause problems with minimizing. You can use a function form instead:

(function(document, window, ...) {
    "use strict";
})(document, window, ...);

There is more explanation on the following stackoverflow-thread: stackoverflow link

"Supermodel-weight" is a really bad tagline.

Might as well say 'anorexic'. Note: switching to size rather than weight and using terms like 'dwarf' or 'midget' probably won't be any better.

Suggested alternatives:

  • featherweight
  • lightweight
  • tiny
  • airy
  • buoyant
  • delicate
  • light and fluffy
  • slight
  • dainty
  • sheer
  • trifling
  • effervescent
  • ethereal
  • frothy
  • gossamery
  • graceful
  • inconsequential
  • insubstantial
  • light-footed
  • lithe
  • meager
  • microscopic
  • nimble
  • nanoscale
  • sprightly
  • trivial

.addClass to add multiple classes, and prevent duplicates being added

Couple of issues:

  1. cannot supply multiple classes
  2. duplicate classes in IE9

1. Multiple Classes

So currently .addClass() allows you to supply a text string with a className but if you add multiple classes such as...

$("#terminator").addClass("no-pity no-remorse no-fear");

... then in modern browsers the .classList property will give a fatal error.
screenshot 141109-154615


2. Duplicate Classes

Another issue is that in IE9 if you do:

$("#terminator").addClass("clothes boots motorcycle");
$("#terminator").addClass("boots");

You would get a result of:

$("#terminator")[0].className === "clothes boots motorcycle boots";
// true

and clearly, a terminator only needs one pair of boots!


Fixes

I have fixed these issues on my branch:
https://github.com/simeydotme/cash/compare/patch-addclass-2

I would love if you could take a looksee and see if it's OK to submit a PR :)

Unit Tests

Hey @kenwheeler @shshaw @thejameskyle , I noticed that the unit tests , specifically for toggleClass and hasClass as I worked on them, seem to be a little lack-lustre... ( see here for the tests I wrote which were not copied: https://github.com/kenwheeler/cash/pull/47/files#diff-c1129c8b045390789fa8ff62f2c6b4a9R50 )

I wonder if we should put a hold on adding / improving features until we've taken a run at improving testing...

The recent growth for this library has been great and it's basically the core of any app that uses it... I think it's important to have extensive test suite in the inevitable situation where a bug is raised we have trouble to crack down on 😄

I'll look at the class-related methods tonight ` and then spend some time to create a milestone/list of what other methods could use more rigorous tests; if everyone else agrees we should take a look at the tests :)

Best, Si.

  • implement Karma / Mocha
  • add back tests for hasClass
  • add back tests for toggleClass

`$.fn.data(obj)`

Support setting multiple data key-value pairs on a collection with $.fn.data using an object, like $.fn.css, $.fn.attr, and $.fn.prop.

please setup ci

... for npm, bower and CDN.

As the ken wheeler himself said:

Seriously though, I need to get CI set up and find some time to give it the hand test prior to a release.

Just wanted to make sure, this issue doesn't get lost... :)

Delegate event binding suggestion

In your delegate event binding (https://github.com/kenwheeler/cash/blob/master/src/events.js#L25) only the direct target is checked, so if the target element has any nested children, this functionality will break.

Here is a really basic jsfiddle to demonstrate http://jsfiddle.net/1786yvmj/.
As you can see, the first alert is never shown because e.target is the span element, while in the second event listener, the loop is used to check all parent nodes, stopping once it's reached the node the event was bound to.

update npm

Would appreciate a new release plus update to npm. Missing loads of useful stuff. E.g. offset

Support for IE8

Right now addEventListener throws this error for IE8:
Object doesn't support this property or method

Method index in docs

It would be super duper coolio if the readme had a clickable index of all the methods to quickly view and hop to a particular method and its use. juss sayin.

add toggleClass()

I dont mean to bloat the module, but toggleClass is widely used.

toggleClass: function (className) {
  var classes = className.match(notWhiteMatch), l, newClassName;

  this.each(function (v) {
    l = classes.length;
      while (l--) {
        v.classList.toggle(classes[l]);
      }
  });

  return this;
}

});

Merge

Before I stumbled across Cash, I tried my hand at a micro jQuery alternative (HalfDollar.js). The size and feature set of Cash is almost perfect, so I don't see a point in trying to continue HalfDollar. I'd like to contribute some of those improvements to Cash, assuming this project is still active.

From my attempt, there are a few improvements that I could merge into Cash, like multiple argument extend, lightweight type checking (isArray, isFunction, etc), and my init function might be a little better.

Another feature that might be worthwhile to add is the smart jQuery Fallback (example on the README) if the necessary methods aren't in browser (primarily querySelectorAll). With the fallback, $.extend, $.fn.extend, and DOM ready calls $(function(){ ... }) will work as expected when jQuery loads.

Would you be interested in me adapting some of these and sending pull requests?

.removeClass() - and other bugs

I found there was a few little problems with the .removeClass() method;

  1. It falsely removes classes (in IE9)
  2. It only allows one class to be removed at a time

Point 1

Consider:

<a class="awesome mcNuggets everything-is-awesome"></a>

... if I wished to remove the class of awesome.. well, it would work in this scenario.
But if the tag looked like:

<a class="everything-is-awesome mcNuggets awesome"></a>

...and I wanted to remove the class awesome then I would be left with:

<a class="everything-is- mcNuggets awesome"></a>

And we all know everything definitely _is not_ mcNuggets. 😢
(run this in IE9: http://jsfiddle.net/453c88f6/)

Point 2

I should be able to do:

cash("a").removeClass("awesome mcNuggets");

and have both my awesome and my mcNuggets removed 😭


I made a branch to fix these issues!
I also fixed up all the unit tests for the .removeClass() method.
https://github.com/simeydotme/cash/compare/fix-closest-and-removeclass?expand=1

perf test
http://jsperf.com/cash-remove-class-speed/3
Now it's interesting to see how goddamned slow the .removeClass() method is in comparison to jQuery on IE9... this is very confusing as just by looking at the code, it appears to be equally or more performant... I can't figure it out, and I guess that's why you mentioned tearing it out into a module?


I also fixed a bug in the .on() delegate method with IE9 to do with checking if a selector matches.
simeydotme@7f3553b

I also fixed the merge-error from the .closest() method that was recently pull-requested... seems that slipped by as both me and @vivekimsit made a PR at same time! 😏
simeydotme@34e9f4e


I know it's such a lot of code/text, and I know you're busy so apologies! 🙇

Error in Google Chrome 44

In the beta version of Google Chrome (v. 44), I get the following error when using .find():

Uncaught TypeError: Cannot set property length of #<NodeList> which has only a getter
cash.extend.fn.extend @ cash.js:90
fn.extend.find @ cash.js:601

Custom Builds

A custom build process that would allow for excluding modules would be useful. Make micro-cash libraries with only the specific features your project needs.

Roadmap

Hey @kenwheeler

Just wondering if you'd consider a roadmap; it may help anyone considering contributing but is afraid they don't have the same vision as you. - Personally I'd like to contribute a bit more but am at a loss where to begin 😄

Regards, Si

$() should accept an existing element.

Imagine the following example:

You are using a third-party library, that returns a raw element object. Now you want to edit this using Cash - how?

var elem = document.createElement("div");
var $e = $(elem); // Error: Can't run querySelectAll on this object.

How could this be made working?

Adding Collaborators

There are quite a few issues that can be closed out ( #78, #55, #51, #48, #39, #15 ) and some simple pull requests that could be easily merged or closed ( #80, #79, #74, #57, #47 ). Since it's a busy time for you right now, it may be worthwhile to add a few collaborators to help manage the cash repo. @simeydotme, @thejameskyle and I have all contributed a good portion of the codebase for cash and could help you keep momentum going. What do you think?

Error using .html() to copy html from one element to another

$("#destination").html($("#source").html()) for copying content from one element to another fails in _.html/_.init

http://codepen.io/anon/pen/DhFHC

It appears that the main _.init function that deals with selector does not handle leading/trailing whitespace. If the innterHMTL has leading whitespace, _.init fails to recognize it as an HTML string.

One thought to address it would be to trim the selector in _.init in the section that checks if it's an HTML string. I can make a pull request if you think that is a reasonable route.

Testing compatibility with bootstrap

I just decided to silently replace jquery.js with cash.js...very sneakily. :)

It seems to actually run down pretty far - my jQuery modules check in properly. But at some point, I see this error:

Uncaught TypeError: this[0].getAttribute is not a function

Cause:

        attr: function (name, value) {
          if (!value) {
       ----> return this[0].getAttribute(name);
          } else {
            this.each(function (v) {
              return v.setAttribute(name, value);
            });

            return this;
          }
        },

I followed the stack trace, and this is the line that causes the error:

$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)

That seems to resolve to bootstrap/src/js/alert.js.

What could the issue be?

cash size

Hi,

it would be nice to document cash aprox size. As a user that "discover" it for the first time I would like to know its weight.

Can you add it aside its description?

CDN link is broken

//cdn.jsdelivr.net/cash/0.0.3/cash.min.js does no work and the latest available version on jsdelivr is 0.0.2

$.extend - TypeError: setting a property that has only a getter

Hello,

I have the following DOM element selected with cash 1.0.0:

var baseElement = $(".editform");

and further down the line I need to change css on elements inside the element. Doing this with jQuery was by using find as I'm trying to do with cash:

baseElement.find(".plain").css({display: "none"});

When this script executes the following errors are reported:

Firefox

...reports the following error: TypeError: setting a property that has only a getter in $.extend (https://github.com/kenwheeler/cash/blob/master/src/util.js#L27)

Chrome

Uncaught TypeError: Cannot set property length of #<NodeList> which has only a getter
cash.extend.fn.extend @ cash.js:91
fn.extend.find @ cash.js:602
enableEditMode @ bidrageditor.js:17
toggleEditMode @ bidrageditor.js:12
onclick @ (index):56

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.