Skip to content

Instantly share code, notes, and snippets.

View jjmu15's full-sized avatar
💭
developering...

Jamie Murphy jjmu15

💭
developering...
View GitHub Profile
@jjmu15
jjmu15 / in_viewport.js
Created January 27, 2014 10:19
check if element is in viewport - vanilla JS. Use by adding a “scroll” event listener to the window and then calling isInViewport().
// Determine if an element is in the visible viewport
function isInViewport(element) {
var rect = element.getBoundingClientRect();
var html = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight) &&
rect.right <= (window.innerWidth || html.clientWidth)
);
@jjmu15
jjmu15 / img_max_width.js
Created January 27, 2014 10:14
Get image max width - This will give us image’s max-width: 100% value in pixels and it’s supported in IE9, Chrome, Firefox, Safari and Opera. We can also take this further and add support for older browsers by loading the image into an in-memory object:
// Get image's max-width:100%; in pixels
function getMaxWidth(img) {
var maxWidth;
// Check if naturalWidth is supported
if (img.naturalWidth !== undefined) {
maxWidth = img.naturalWidth;
// Not supported, use in-memory solution as fallback
} else {
@jjmu15
jjmu15 / has_class.js
Created January 27, 2014 10:08
has class function - vanilla JS. Check if element has specified class
// hasClass, takes two params: element and classname
function hasClass(el, cls) {
return el.className && new RegExp("(\\s|^)" + cls + "(\\s|$)").test(el.className);
}
/* use like below */
// Check if an element has class "foo"
if (hasClass(element, "foo")) {
@jjmu15
jjmu15 / dollar_selector.js
Created January 27, 2014 10:07
Create $ selector in vanilla JS
// This gives us simple dollar function and event binding
var $ = document.querySelectorAll.bind(document);
Element.prototype.on = Element.prototype.addEventListener;
@jjmu15
jjmu15 / remove_class.js
Created January 27, 2014 10:07
Remove specified class - vanilla JS
// removeClass, takes two params: element and classname
function removeClass(el, cls) {
var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
el.className = el.className.replace(reg, " ").replace(/(^\s*)|(\s*$)/g,"");
}
@jjmu15
jjmu15 / for_each_class.js
Created January 21, 2014 13:52
Vanilla js - for each class
var myObj = document.getElementsByClassName('class');
for (var i = 0; i < myObj.length; ++i) {
var item = myObj[i];
item.innerHTML = 'this is value';
}