Tuesday, November 22, 2016

Load Only a Section of a Page

Use Case

You want to AJAX load a section of another page on your site onto the current page. Say your eCommerce CMS system creates a dynamic menu of products, but that exists as a subdirectory of your site and you want to use that on the homepage.

#JQuery

$("#mainNav").load("/store #mainNav")

The first param is the URL (only works for same-domain requests!) and the 
second (well, technically it's still part of the first, separated by a space) is a jQuery selector
 of the part to load. Not passing the second selector param will load the entire page. 
There is an optional third parameter, a callback function, which will run when the load is 
complete.

Load jQuery Only If Not Present

Say you were going to do an include on a whole bunch of pages, and inside of that include you wanted to do some jQuery specific stuff. That page may or may not already have jQuery loaded. If it already does, you don't want to load it again, but if not, you do. This works for that.

Smart Asynchronous Way
// Only do anything if jQuery isn't defined
if (typeof jQuery == 'undefined') {

 if (typeof $ == 'function') {
  // warning, global var
  thisPageUsingOtherJSLibrary = true;
 }
 

jQuery Duplicate Plugin

$.fn.duplicate = function(count, cloneEvents) {
       var tmp = [];
       for ( var i = 0; i < count; i++ ) {
               $.merge( tmp, this.clone( cloneEvents ).get() );
       }
       return this.pushStack( tmp );
};

The .clone() function of jQuery will duplicate a set once, but what if you need multiple 
copies of the same set? You would have to do:

$(elem)
   .clone()
   .appendTo(otherElem)
   .clone()
   .appendTo(otherElem)
   .clone()
   .appendTo(otherElem);
Now you can just:

$(elem)
   .duplicate(n)
   .appendTo(otherElem);
The first parameter is the number of clones you want and the second optional parameter 
is a boolean which controls if you want the events bound to those existing elements to be attached to the clones as well (or not).

Force iframe to Reload

$('iframe').attr('src', $('iframe').attr('src'));

Fallback for CDN hosted jQuery

Several big companies offer copies of jQuery hosted on their CDN's (Content Delivery Network). Most notoriously Google, but also Microsoft and jQuery themselves. A lot of people swear by this since it saves bandwidth, downloads faster, and perhaps even stays cached jumping between different sites that use the same script.
There is always that twinge of doubt though, that perhaps something goes wrong with these big companies CDN at the script isn't available (it happens). It's more reliable to use your own website, as hey, if they are loading your webpage, then your server is up and will server the script just fine, albeit with out the benefits of the CDN.
So perhaps the best solution is to use both methods! Use the CDN first, and if it fails, load the local copy. Here is a technique:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
    document.write(unescape("%3Cscript src='/js/jquery-1.4.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

Find all Internal Links

Find all links that start with the sites domain, a slash, relative file path, or a hashtag.
var siteURL = "http://" + top.location.host.toString();

var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

Draggable without jQuery UI

It doesn't have all the fancy callbacks and options, but hey, it makes things draggable (and with a specified handle optionally).
(function($) {
    $.fn.drags = function(opt) {

        opt = $.extend({handle:"",cursor:"move"}, opt);

        if(opt.handle === "") {
            var $el = this;
        } else {
            var $el = this.find(opt.handle);
        }

        return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
            if(opt.handle === "") {
                var $drag = $(this).addClass('draggable');
            } else {
                var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
            }
            var z_idx = $drag.css('z-index'),
                drg_h = $drag.outerHeight(),
                drg_w = $drag.outerWidth(),
                pos_y = $drag.offset().top + drg_h - e.pageY,
                pos_x = $drag.offset().left + drg_w - e.pageX;
            $drag.css('z-index', 1000).parents().on("mousemove", function(e) {
                $('.draggable').offset({
                    top:e.pageY + pos_y - drg_h,
                    left:e.pageX + pos_x - drg_w
                }).on("mouseup", function() {
                    $(this).removeClass('draggable').css('z-index', z_idx);
                });
            });
            e.preventDefault(); // disable selection
        }).on("mouseup", function() {
            if(opt.handle === "") {
                $(this).removeClass('draggable');
            } else {
                $(this).removeClass('active-handle').parent().removeClass('draggable');
            }
        });

    }
})(jQuery);

Usage
$('div').drags();

Display Browser and Version

This is jQuery specific, and contains a bit of a hack/fix for dealing with Chrome. This works between jQuery 1.5.1 and jQuery 1.8.3. It's gone in jQuery 1.9. Presumably because it was used too improperly too frequently and it was hurting the web. Better to feature detect when possible.
var userAgent = navigator.userAgent.toLowerCase(),
    browser   = '',
    version   = 0;

$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

// Is this a version of IE?
if ($.browser.msie) {
  userAgent = $.browser.version;
  userAgent = userAgent.substring(0,userAgent.indexOf('.')); 
  version = userAgent;
  browser = "Internet Explorer";
}

// Is this a version of Chrome?
if ($.browser.chrome) {
  userAgent = userAgent.substring(userAgent.indexOf('chrome/') + 7);
  userAgent = userAgent.substring(0,userAgent.indexOf('.')); 
  version = userAgent;
  // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
  $.browser.safari = false;
  browser = "Chrome";
}

// Is this a version of Safari?
if ($.browser.safari) {
  userAgent = userAgent.substring(userAgent.indexOf('safari/') + 7); 
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
  version = userAgent; 
  browser = "Safari";
}

// Is this a version of Mozilla?
if ($.browser.mozilla) {
 //Is it Firefox?
 if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
  userAgent = userAgent.substring(userAgent.indexOf('firefox/') + 8);
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
  version = userAgent;
  browser = "Firefox"
 }
 // If not then it must be another Mozilla
 else {
   browser = "Mozilla (not Firefox)"
 }
}

// Is this a version of Opera?
if ($.browser.opera) {
 userAgent = userAgent.substring(userAgent.indexOf('version/') + 8);
 userAgent = userAgent.substring(0,userAgent.indexOf('.'));
 version = userAgent;
 browser = "Opera";
}

// Now you have two variables, browser and version
// which have the right info

Check if Event was Triggered or Native

$('button').click(function(event, wasTriggered) {
    if (wasTriggered) {
        alert('triggered in code');
    } else {
        alert('triggered by mouse');
    }
});

$('button').trigger('click', true);

Check if jQuery is Loaded

if (typeof jQuery == 'undefined') {

    // jQuery IS NOT loaded, do stuff here.

}

Tuesday, October 18, 2016

Transparent Circular Loader

<div class="util-bar">
 <label for="">Change Background: </label>
  <button class="green"></button>
  <button class="teal"></button>
  <button class="blue"></button>
  <button class="pink"></button>
  <button class="red"></button>
  <button class="orange"></button>
  <button class="abstract"></button>
  <button class="nature"></button>
  <button class="food"></button>
</div>
<div class="loader">
  <span class="spinner"></span>
  Loading
</div>
Test here

Autofill submit button

<span>Required:</span> <input required=required type="text"> <br>
<span>Required:</span> <input required=required type="text"> <br>
<span>Required:</span> <input required=required type="text"> <br>
<span>Required:</span> <input required=required type="text"> <br>
<div>
  <button>Send</button>
</div>

Test here

Saturday, September 24, 2016

Better Broken Image Handling

Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.
// Replace source
$('img').error(function(){
        $(this).attr('src', 'missing.png');
});

// Or, hide them
$("img").error(function(){
        $(this).hide();
});

Change WMode with jQuery

If you don't set the wmode on a flash embed it will float over the top of an overlay which can be a pretty big deal. This is ideal in environment with lots of legacy video code or where users will be posting new code and teaching them about wmode is a lost cause. This should work in all browsers.

$("embed").attr("wmode", "opaque");
var embedTag;
$("embed").each(function(i) {
       embedTag = $(this).attr("outerHTML");
       if ((embedTag != null) && (embedTag.length > 0)) {
               embedTag = embedTag.replace(/embed /gi, "embed wmode="opaque" ");
               $(this).attr("outerHTML", embedTag);
       } else {
               $(this).wrap("<div></div>");
       }
});

Saturday, September 17, 2016

Button to refresh web page



Allow visitors of your web page to interface with the browser reload function to get the latest information and to interface with other JavaScript's, such as ourrandom quote script.
<FORM>
<INPUT Type="button" VALUE="Reload Page" onClick="history.go(0)">
</FORM>

Send viewer back to where they came from

Is your web page under construction or do you not want visitors, or want to make your visitor get a little mad? Copy this script that makes the browser go back to the page that the viewer came from.
<script type="text/javascript">
setTimeout("history.back();", 7000);
</script>

Disable mouse right-click





<script language="JavaScript" Type="text/javascript">
<!--
function popupMsg(theMsg) {
alert(theMsg);
}
//-->
</script>

Change background color depending on time of day

<script type="text/javascript">
var now = new Date();
var hours = now.getHours();

//Keep in code - Written by Computerhope.com
//Place this script in your HTML heading section

document.write('It\'s now: ', hours, '<br><br>');
document.bgColor="#CC9900";

//18-19 night
if (hours > 17 && hours < 20){
document.write ('<body style="background-color: orange">');
}
//20-21 night
else if (hours > 19 && hours < 22){
document.write ('<body style="background-color: orangered">');
}
//22-4 night
else if (hours > 21 || hours < 5){
document.write ('<body style="background-color: #C0C0C0;">');
}
//9-17 day
else if (hours > 8 && hours < 18){
document.write ('<body style="background-color: #616D7E">');
}
//7-8 day
else if (hours > 6 && hours < 9){
document.write ('<body style="background-color: skyblue">');}
//5-6 day
else if (hours > 4 && hours < 7){
document.write ('<body style="background-color: steelblue">');
}
else {
document.write ('<body style="background-color: white">');
}
</script>

Create a random website background color every five seconds

<script type="text/javascript">
function setbackground()
{
window.setTimeout( "setbackground()", 5000); // 5000 milliseconds delay

var index = Math.round(Math.random() * 9);

var ColorValue = "FFFFFF"; // default color - white (index = 0)

if(index == 1)
ColorValue = "FFCCCC"; //peach
if(index == 2)
ColorValue = "CCAFFF"; //violet
if(index == 3)
ColorValue = "A6BEFF"; //lt blue
if(index == 4)
ColorValue = "99FFFF"; //cyan
if(index == 5)
ColorValue = "D5CCBB"; //tan
if(index == 6)
ColorValue = "99FF99"; //lt green
if(index == 7)
ColorValue = "FFFF99"; //lt yellow
if(index == 8)
ColorValue = "FFCC99"; //lt orange
if(index == 9)
ColorValue = "CCCCCC"; //lt grey

document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;

}
</script>
<body onload="setbackground();">

How to Put Google Adsense Below Post Title in Blogger?

Adsense is used by  majority  of expert bloggers for their website monetization because it is a cookie based contextual advertising syste...