Saturday, 24 January 2015

, ,

CSS Class Change, Add, Remove, Replace with JavaScript and jQuery

"The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class." --W3

To Change/Replace CSS Class with Javascript (cross-browser):

To replace all existing classes with one or more new classes, set the 'className' attribute by fetching element in DOM using getElementById or getElementsByClassName or getElementsByTagName...
 document.getElementById("IDofElement").className = "MyClass";
//For Multiple Classes, use a space-delimited list //e.g. "MyClass MyClass1 MyClass2"

Add an Additional Class to an element using Javascript:

To add a class or more than one class to an element, without affecting/replacing/removing existing classes/values, append a space in start and the new classname, like:
document.getElementById("IDofElement").className += " MyClass";
//For Multiple Classes, use a space-delimited list
//e.g. " MyClass MyClass1 MyClass2"

Remove a Class with Javascript:

To remove a(single) class  with javascript to an element without altering any other classes (in case there are more than one.):
document.getElementById("IDofElement").className = document.getElementById("IDofElement").className.replace( /(?:^|\s)MyClass(?!\S)/g , '' )
//Regex Explanation
//(?:^|\s) -- checks and match the start of the string, or single whitespace character
//MyClass  -- the literal(name) text for the class to remove
//(?!\S)   -- lookahead to verify the above is the whole classname, ensures end of string or a space.

Check if a Class is already applied:

if ( document.getElementById("IDofElement").className.match(/(?:^|\s)MyClass(?!\S)/) )
//For Regex Explanation look previous code

Assigning above actions to an event:

function modifyClass(){
        document.getElementById("IDofElement").className = "MyClass";
        //or any other code example from above
}
window.onload = function(){
        document.getElementById("IDofElement").addEventListener( 'click' , modifyClass );
       //in this case addEventListener is listening to click event
      //but we can use any event depending on our use
}

To ADD Class with jQuery:

$('#IDofElement').addClass('MyClass');

Remove a Class with Javascript:

$('#IDofElement').removeClass('MyClass');

Check if a Class is already applied:

if ( $('#IDofElement').hasClass('MyClass') ){
 //any code here
};

Toggle/Swap between two Classes:

$('#IDofElement').toggleClass('MyClass');

Assigning above actions to an event:

$('#IDofElement').click(changeClass); 

Friday, 23 January 2015

,

Unable Selection With CSS

Just apply this CSS to your HTML element & this CSS rule will disable text selection highlighting.

.className {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

Thursday, 22 January 2015

,

When to use img vs. background-image in CSS ?

Proper uses of IMG tag

Use IMG if you intend to have people print your page and you want the image to be included by default.
Use IMG (with alt text) when the image has an important semantic meaning, such as a warning icon. This ensures that the meaning of the image can be communicated in all user-agents, including screen readers.

Pragmatic uses of IMG

Use IMG if you intend to have people print your page and you want the image to be included by default.
Use IMG if you rely on browser scaling to render an image in proportion to text size.
Use IMG for multiple overlay images in IE6.
Using img instead of background-image can dramatically improve performance of animations over a background.

When to use CSS background-image

Use CSS background images if the image is not part of the content.
Use CSS background images when doing image-replacement of text eg. paragraphs/headers.
Use background-image if you intend to have people print your page and you do not want the image to be included by default.
Use background-image if you need to improve download times, as with CSS sprites.
Use background-image if you need for only a portion of the image to be visible, as with CSS sprites.
Use background-image with background-size:cover in order to stretch a background image to fill its entire window.

In short
Foreground = img.
Background = CSS background.
,

Horizontally Center a Div in a Div

How to horizontally center a div inside a div with CSS ? e.g
<div id="outer">
<div id="inner">
This is inner one...</div>
</div>
It is very simple, just apply this css.
#outer {
width: 100%;
}
#inner {
width: 50%;
margin: 0 auto;
}
Or If you don't want to set a fixed width on the inner div you could do something like this:
#outer {
width: 100%;
text-align: center;
}

#inner {
display: inline-block;
}
That makes the inner div an inline element that can be centered with text-align.

Box Model

#outer{
    width:100%;

    /* Firefox */
    display:-moz-box;
    -moz-box-pack:center;
    -moz-box-align:center;
    /* Safari and Chrome */
    display:-webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;

    /* standard */
    display:box;
    box-pack:center;
    box-align:center;
}

#inner{
    width:50%;
}

Another way with Box Model:

#outer {
    width:100%;
    height:100%;
    display:box;
    box-orient:horizontal;
    box-pack:center;
    box-align:center;
}

Wednesday, 21 January 2015

Basic HTML5 Page Structure

<!doctype html>
<html>

<head>
<meta charset="utf-8" />
<title>Your Website</title>
 <link href="main.css" rel="stylesheet" type="text/css"></link>
<script src="script.js"></script>
</head>
<body>
<header>
<nav>
<ul>
<li>Home</li>
<li>About</li>
</ul>
</nav>
</header>

<section>
<article>
<header>
<h2>Article title</h2>
Posted on <time datetime="2009-09-04T16:31:24+02:00">September 4th 2009</time> by <a href="#">Writer</a> - <a href="#">6 comments</a>
</header>
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egest.

</article>

<article>
<header>
<h2>Article title</h2>
Posted on <time datetime="2009-09-04T16:31:24+02:00">September 4th 2009</time> by <a href="#">Writer</a> - <a href="#">6 comments</a>
</header>
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
</article>
</section>

<aside>
<h2>About section</h2>
Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
</aside>

<footer>
Copyright 2009 Your name
</footer>
</body>
</html>

Include a JavaScript file in another JavaScript file?

Ever wondered including a JavaScript file inside another JavaScript, it is basically like embedding or invoking other file from inside a file, just like @import in CSS. Well there is no @import like mehtod but it could be achieved.

jQuery Loading

jQuery provides a loading functionality using getScript method. We can load JS files using this method except we could not use it to load jQuery itself.
$.getScript("myScript.js", function(){
alert("Script loaded and executed."); // Use anything defined in the loaded script...
});

Dynamic Script Loading with JavaScript


function loadScript(url, callback)
{
// Adding the script tag to the head
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
script.onreadystatechange = callback;
script.onload = callback;
// There are several events for cross browser compatibility.

// Fire the loading
head.appendChild(script);
}
Then you write the code you want to use AFTER the script is loaded:
var myCoding = function() {
// Here, do what ever you want
};
Then you run all that:
loadScript("mainScript.js", myCoding);

Ajax Loading

Load an additional script with an Ajax call and then use eval. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also makes you code vulnerable.

Search Substring within a String using JavaScript/jQuery

Different approaches could be used to search a substring.
Using indexOf returns the position of the string in the other string. If not found, it will return -1:
var s = "This is some String in Javascript assigned to a variabel..blah blah.";
alert(s.indexOf("script") > -1);

We could also use the JavaScript search() method. Syntax is: string.search(regexp);
It returns the position of the match, or -1 if no match is found.
You don't need a complicated regular expression syntax. If you are not familiar with them a simple st.search("title") will do. If you want your test to be case insensitive, then you should do st.search(/title/i).

string.includes has been added to JavaScript's next version, ES6 (ECMAScript6):
"potato".includes("to");
> true
//Note you may need to load es6-shim or similar to get this working on older browsers.
require('es6-shim')

jQuery's :contains selector could also be used. Though it searches DOM, but if the string you're searching through happens to be located within a DOM element, jQuery's :contains selector can be used
$("div:contains('something')")

Redirect With JavaScript/jQuery

To Redirect a page with Javascript or jQuery different methods or styles could be used.
window.location.href="http://www.someUrl.com";   // similar behavior as clicking on a link

window.location = http://www.someUrl.com;

window.location.replace("http://www.someUrl.com");   // similar behavior as an HTTP redirect

window.location.assign("http://www.someUrl.com");

document.location.href = 'http://www.someUrl.com';

self.location="http://www.someUrl.com";

top.location="http://www.someUrl.com";

window.navigate("http://www.someUrl.com");   // old-IE-only

$(location).attr('href',"http://www.someUrl.com");   //jQuery

Possible Solutions:

With jQuery:
var url = "http://someUrl.com";  
$(location).attr('href',url);

A Cross Browser Fix:

This cross-browser fix is a simple function. With this function you don't have to worry about HTTP_REFERER getting lost.
function Redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);

// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}

// All other browsers
else { window.location.href = url; }
}

Redirect('someUrl.html'); //function call with URL argument

Toggle Visibility With JavaScript/jQuery

Is it possible to toggle the visibility of an element, using the JavaScript/jQuery functions ? [ .hide(), .show() or .toggle(). etc ]
Also, how to test if an element is visible or hidden?

If you are looking for a single element, this simple piece of code will work.
// Checks display:[none|block], ignores visible:[true|false]
$(element).is(":visible");

The hidden selector could also be used:
// Matches all elements that are hidden
$('element:hidden')

And the visible selector:

// Matches all elements that are visible
$('element:visible')
There is another detailed way of doing this:
$(".item").each(function() {
if ($(this).css("visibility") == "hidden") {
// handle non visible state
} else {
// handle visible state
}
});

This could also be achieved using plain JavaScript, & this
Works everywhere
Works for nested elements
Works for CSS and inline styles
Doesn't require a framework

function isRendered(domObj) {

    if ((domObj.nodeType != 1) || (domObj == document.body)) {

        return true;

    }

    if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {

        return isRendered(domObj.parentNode);

    } else if (window.getComputedStyle) {

        var cs = document.defaultView.getComputedStyle(domObj, null);

        if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {

            return isRendered(domObj.parentNode);

        }

    }

    return false;

}

These are also some useful jQuery Methods,

$('.target').toggle();

$('.target').slideToggle();

$('.target').fadeToggle();

Monday, 19 January 2015

Refresh a Page with Javascript or jQuery?

Wondering how to refresh page with JavaScript or jQuery? It's quite easy..

Method 1:

$('#someid').click(function() {

    location.reload();

});

The reload() function takes an optional Boolean parameter that can be set to true to reload from the server rather than the cache. The parameter defaults to false, so by default the page reloads from the browser's cache.

Method 2-6:

All these methods need to be attached to some event in order to work.

history.go(0);

location.reload();

history.go(0);

location.href = location.href;

location.href = location.pathname;

location.replace(location.pathname)

How to Empty an array in JavaScript?

For instance,
A is an array in a JavaScript program.
A = [1,2,3,4];
How to empty that?
By empty we mean Clear/Clean the Array and not delete or remove Array itself in this case A.

Method 1:


//Set A to a new empty array
A = [];

Its that simple. This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

Method 2:


//Set arrat length to zero 0
A.length = 0
This will clear the existing array by setting its length to 0. It also works when using "strict mode" in Ecmascript 5(JS5) because the length property of an array is a read/write property.

Method 3:


//Using Splice method
A.splice(0,A.length)
Using .splice() will work perfectly, but it's not very efficient because the .splice() function will return an array with all the removed items, so it will actually return a copy of the original array.

Method 4:

This solution is not very succinct but it is by far the fastest solution (apart from setting the array to a new array). If you care about performance, consider using this method to clear an array. Benchmarks show that this is at least 10 times faster than setting the length to 0 or using splice().

//using while loop with pop method
while(A.length) {
    A.pop();
}

How To Dynamically Load a JavaScript or CSS file

In order to load a JavaScript file dynamically different methods can be used, here are a few:

Method 1: 

Simply create an include function to handle both script and css files. This function also checks to make sure that the script or CSS file hasn't already been loaded dynamically.
function include( url, type ){
// First make sure it hasn't been loaded by something else.
if( Array.contains( includedFile, url ) )
return;

// Determine the MIME-type
var jsExpr = new RegExp( "js$", "i" );
var cssExpr = new RegExp( "css$", "i" );
if( type == null )
if( jsExpr.test( url ) )
type = 'text/javascript';
else if( cssExpr.test( url ) )
type = 'text/css';

// Create the appropriate element.
var tag = null;
switch( type ){
case 'text/javascript' :
tag = document.createElement( 'script' );
tag.type = type;
tag.src = url;
break;
case 'text/css' :
tag = document.createElement( 'link' );
tag.rel = 'stylesheet';
tag.type = type;
tag.href = url;
break;
}

// Insert it to the and the array to ensure it is not
// loaded again.
document.getElementsByTagName("head")[0].appendChild( tag );
Array.add( includedFile, url );
}

Note: "includedFile" and "Array" variables must be defined.

Method 2:

  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
for (var i = 0, l = js.length; i < l; i++) {
document.getElementsByTagName("head")[0].innerHTML += ("");
}
Same method using JQuery
  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];
var $head = $("head");
for (var i = 0; i < js.length; i++) {
$head.append("");
}

Method 3:

Using Jquery getScript Method.
   $.getScript("my_lovely_script.js", function(){
// here you can use anything you defined in the loaded script
});

Method 4: 

Another Simpler Method using plain JS
function include(url)
{
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
s.setAttribute("src", url);
var nodes = document.getElementsByTagName("*");
var node = nodes[nodes.length -1].parentNode;
node.appendChild(s);
}
, ,

Set CSS background color of an HTML element via JavaScript?

In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So background-color becomes backgroundColor.
,

Auto Refresh Browser With Change In HTML, CSS, Javascript

Refreshing browser after making changes in HTML,CSS Or Js files during development is very tidy process. You may want to check this google chrome extension, it makes things easy. I've checked many but this is the best one i found.

LivePage reloads website resources (such as HTML, CSS, LESS, and JavaScript) as they change on the server/localhost.
LivePage is a developer tool which reloads website resources (such as CSS, LESS, HTML and JavaScript) as they change on the server, so you are always looking at the most up-to-date version of a web page. It can make developing websites a lot faster, by helping productivity.

Key features are:
  * LESS support
  * Entire domains can be made live
  * file:// protocol is now supported

It's recommended you use this extension in a development environment (Such as XAMPP). But it works fine even without XAMPP Or LAMP etc.

All future milestones & current issues can be found on https://github.com/MikeRogers0/LivePage/issues
,

How to detect which font was used in a web page?

Scenario:

Suppose, your Font contains 'glyphs' not available in other fonts and when the user does not have it you may want to display a link asking the user to download that font so they can view it exactly as you want.

Solution:

JFont Checker:

This is a tool for webpages to check if the font is installed. Detect installed fonts on client's machine using JFont Checker.

Basically, an element is set to use a specific font and a string is set to that element. If the font set for the element does not exist, it takes the font of the parent element. So, what they do is measure the width of the rendered string. If it matches what they expected for the desired font as opposed to the derived font, it's present.

Also Check: Javascript/CSS Font Detector