--------------------jQuery highlight specific text (with plug-in)

$(function(){ $('*').highlight('ABC'); })

--------------------jQuery 2 Tab Folder

.hide { display:none; } $(function(){ $('#redTab').click(function(){ $('#content1').show() $('#content2').hide() }) $('#blueTab').click(function(){ $('#content2').show() $('#content1').hide() }) })

--------------------jQuery red text for spans containing *, then drop *

$(function(){ $('span:contains("*")').attr('class','red'); $('*').each(function(){ $(this).html( $(this).html().replace(/[*]/g,'') ) }) });

--------------------jQuery change content (append, prepend, etc.)

$(function(){ $('span:eq(0)').text('my new text'); $('span:eq(1)').html('my new html '); $('span:eq(2)').append(' my new appended content'); $('span:eq(3)').prepend('my new prepended content '); });

--------------------Two direction slider

var picArray = new Array('images/blue.jpg','images/red.jpg','images/green.jpg','images/yellow.jpg','images/purple.jpg','images/orange.jpg'); var curPic = 0; function initAll(){ document.getElementById("back").onclick = goBack; document.getElementById("forward").onclick = goForward; } function goBack(){ if(curPic == 0){ curPic = picArray.length}; curPic -- ; document.getElementById("myImage").src = picArray[curPic]; return false; } function goForward(){ curPic ++ ; if(curPic == picArray.length){ curPic = 0 }; document.getElementById("myImage").src = picArray[curPic]; return false; } window.onload = initAll;

--------------------Random image slider

var picArray = new Array('images/blue.jpg','images/red.jpg','images/green.jpg','images/yellow.jpg','images/purple.jpg','images/orange.jpg'); function initAll(){ document.getElementById("butt1").onclick = newPic; } function newPic(){ var i = Math.floor(Math.random()* picArray.length); document.getElementById("myImage").src = picArray[i]; } window.onload = initAll;

--------------------jQ change size of object

$(function(){ $('#butt1').click(function(){ $('#myImage').width('200'); $('#myImage').height('200'); }) })

--------------------jQ toggle image

$(function(){ $('#butt1').click(function(){ $("#myImage").toggle("slow"); }) })

--------------------Reverse Text

function revIt(){ var i = document.getElementById("alpha").innerHTML; var j = new Array(); j = i.split(''); j = j.reverse(); k = j.join(''); document.getElementById("alpha").innerHTML = k; } function initAll(){ document.getElementById("butt1").onclick = revIt; } window.onload = initAll;

--------------------jQ Reverse Text

$(function(){ $('#butt1').click(function(){ var i = $('#alpha').text(); var j = new Array(); j = i.split(''); j = j.reverse(); k = j.join(''); $('#alpha').text(k); }) });

--------------------jQ Change body content (prepend, append, etc.)

$(function(){ $('#butt1').click(function(){ $('body').prepend('new content'); $('body').append('new content'); $('body').html(''); }) });

--------------------jQ switch div contents

$(function(){ var i = $('#one').html(); var j = $('#two').html(); $('#butt1').click(function(){ $('#one').html(j); $('#two').html(i); }) });

--------------------jQ fade-in image

$(function(){ var i = $('#myImage').height(); $("#images").css('height',i); $('#myImage').hide(); $('#butt1').click(function(){ $('#myImage').fadeIn('slow') }); }); //$('#myImage').show();

--------------------jQ animate image

$(function(){ $('#images').css('position','relative'); $('#images').animate({ opacity: 0.25, left: '+=250' }, 5000, function(){ }); });

--------------------jQ toggle between two options

login form

--------------------Open new window

function newWin(){ window.open("http://www.google.com","myWin","height=100, width=200") }

--------------------Populate variable into new window

function newWin(){ var i = document.getElementById('myTextBox').value; myWindow=window.open('','','width=200,height=100') myWindow.document.write(i) myWindow.focus() }

--------------------Change to new URL

function changeURL(){ //var i = "http://www.google.com/"; //window.location = (i) window.location = "http://www.google.com/"; }

--------------------Rate cars

function rateIt(){ var b = document.getElementById("blue").value; var r = document.getElementById("red").value; var g = document.getElementById("green").value; var carOrder = new Array(); carOrder[b] = "Blue Car"; carOrder[r] = "Red Car"; carOrder[g] = "Green Car"; carOrder.join(','); document.getElementById('rateCar').innerHTML = "

" + carOrder + "

"; } Blue Car: Red Car: Green Car:

--------------------Prototype example

function employee(name,jobtitle,born) { this.name=name; this.jobtitle=jobtitle; this.born=born; } var fred = new employee("Fred Flintstone","Caveman",1970); employee.prototype.salary = null; fred.salary=20000; document.write(fred.salary);

--------------------Self calling function

(function(){ alert('test'); })();

--------------------setTimeout, setInterval

setTimeout(function() {
alert('test')
}, 5000);

--------------------Event Listeners

function addEventHandler(Node, evt, Func, Captures) {
if (document.addEventListener) {
// Safari, Chrome, Fx, etc
Node.addEventListener(evt, Func, Captures);
} else {
// IE
Node.attachEvent('on' + evt, Func);
}
}

function onLinkClicked(e) {
alert("You clicked the link!");
}

function setUpClickEvent(e) {
addEventHandler(document.getElementById('butt1'), 'click', onLinkClicked, false);
}

window.onload = setUpClickEvent

--------------------Javascript create and remove Element

function newContent(){ var divTag = document.createElement("div"); divTag.id = "div1"; divTag.setAttribute("align","center"); divTag.style.margin = "0px auto"; divTag.className ="dynamicDiv"; divTag.innerHTML = "This HTML Div tag created using Javascript DOM dynamically."; document.body.appendChild(divTag); };

 

function removeNode(){
var child = document.getElementById('alpha');
var parent = document.getElementById('two');
parent.removeChild(child);
}

--------------------Javascript For Loop

function myFunc(){
var i =0;
for(i=0; i<= picArray.length; i++)
{ var value = picArray[i];
document.write(value + '<br />');
}
}

 

document.write("<h1>Multiplication table</h1>");
document.write("<table border=2 width=50%");

for (var i = 1; i <= 9; i++ ) { //this is the outer loop
document.write("<tr>");
document.write("<td>" + i + "</td>");

for ( var j = 2; j <= 9; j++ ) { // inner loop
document.write("<td>" + i * j + "</td>");
}

document.write("</tr>");
}

document.write("</table>");

 

 

<script type="text/javascript">

function howMany (selectItem) {
  var numberSelected=0

  for (var i=0; i < selectItem.options.length; i++) {
     if (selectItem.options[i].selected == true)
       numberSelected++;
  }

  return numberSelected
}

</script>

<form name="selectForm">
<p>Choose some book types, then click the button below:</p>
<select multiple name="bookTypes" size="8">
<option selected> Classic </option>
<option> Information Books </option>
<option> Fantasy </option>
<option> Mystery </option>
<option> Poetry </option>
<option> Humor </option>
<option> Biography </option>
<option> Fiction </option>
</select>
<input type="button" value="How many are selected?"
onclick="alert ('Number of options selected: ' + howMany(document.selectForm.bookTypes))">
</form>

 

--------------------jq remove and add list item

$('.tList li:eq(2)').remove(); $(".tList ul").append('
  • new list item
  • ');

    --------------------php connect and query

    ?php // Make a MySQL Connection mysql_connect("host", "user", "password") or die(mysql_error());
    mysql_select_db("test") or die(mysql_error()); // Retrieve all the data from the "example" table
    $result = mysql_query("SELECT * FROM example") or die(mysql_error());
    $row = mysql_fetch_array( $result );// store the record of the "example" table into $row // Print out the contents of the entry echo "Name: ".$row['name']; echo " Age: ".$row['age']; ?>

    --------------------jQuery display location

    $(function(){ var pathname = window.location.pathname; $('#one').text(pathname); })

    --------------------jQuery slide, delay, fade

    $(function(){ $('#myImage').slideUp(300).delay(800).fadeIn(400); })

    --------------------change string to number then number to string

    var b = document.getElementById('blue').value; var b1 = Number(b);

    (ABOVE FOR FORM)

    var i = '12';
    function myFunc(){
    alert(i);
    alert(typeof i);
    i = Number(i);
    alert(typeof i);
    alert(i);
    i = String(i);
    alert(typeof i);
    alert(i);
    }

    --------------------jQuery each method

    $(function(){ $.each(/*picArray*/[52, 97], function(index, value) { alert(index + ': ' + value); }); })

    $(document.body).click(function () {
    $("div").each(function () {
    if (this.style.color != "blue") {
    this.style.color = "blue";
    } else {
    this.style.color = "";
    }
    });
    });

    $(function(){
    $('li:odd').each(function(){
    $(this).css("background-color","orange");
    $(this).fadeOut(2000);
    }) }) --------------- $('a').each(function(index, value){ $('#myDiv').append('
    ' + $(this).attr('href')); }) JQUERY4U PHP4U BLOGOOLA ------------------------ var myJSON = [ { "red": "#f00" }, { "green": "#0f0" }, { "blue": "#00f" } ]; $(function() { $.each(myJSON, function() { $.each(this, function(name, value) { /// do stuff console.log(name + '=' + value); }); }); //outputs: red=#f00 green=#0f0 blue=#00f }) -------------------------------- $('li').each(function(i){ $(this).delay(i*1500).fadeOut(1500,function(){ $(this).next().css('background-color','yellow'); }); }); ----------------

    --------------------Javascript Create iFrame with Attributes

    function myFunc(){ var newCon = document.createElement('iframe'); newCon.setAttribute('src', 'http://www.bing.com/'); newCon.setAttribute('width', '600'); newCon.setAttribute('height', '200'); document.getElementById('two').appendChild(newCon) }

    --------------------jQuery insert content before and after without losing existing content

    $(function(){
    $('<li>new content here</li>').insertAfter('.tList li:eq(3)');
    $('<div>Hey</div>').insertBefore('span');
    })

    --------------------jQuery clone and position existing content elsewhere on page

    $(function(){
    $('span:contains("*")').clone().appendTo('#one');
    })

    --------------------jQuery empty and detach content

    $(function(){ $('span:contains("*")').empty(); $('ul').detach('.tList');//saves data in detached set })

    --------------------jQuery browser sniffer

    $(function(){ $.each(jQuery.browser, function(i, val) { if ($.browser.msie) { alert( "this is webkit!" ); } else{ alert( "this is not IE" ); } }) })

    ----------------------------------------( full blown veersion below)

    var nVer = navigator.appVersion;
    var nAgt = navigator.userAgent;
    var browserName = navigator.appName;
    var fullVersion = ''+parseFloat(navigator.appVersion);
    var majorVersion = parseInt(navigator.appVersion,10);
    var nameOffset,verOffset,ix;

    // In Opera, the true version is after "Opera" or after "Version"
    if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
    browserName = "Opera";
    fullVersion = nAgt.substring(verOffset+6);
    if ((verOffset=nAgt.indexOf("Version"))!=-1)
    fullVersion = nAgt.substring(verOffset+8);
    }
    // In MSIE, the true version is after "MSIE" in userAgent
    else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
    browserName = "Microsoft Internet Explorer";
    fullVersion = nAgt.substring(verOffset+5);
    }
    // In Chrome, the true version is after "Chrome"
    else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
    browserName = "Chrome";
    fullVersion = nAgt.substring(verOffset+7);
    }
    // In Safari, the true version is after "Safari" or after "Version"
    else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
    browserName = "Safari";
    fullVersion = nAgt.substring(verOffset+7);
    if ((verOffset=nAgt.indexOf("Version"))!=-1)
    fullVersion = nAgt.substring(verOffset+8);
    }
    // In Firefox, the true version is after "Firefox"
    else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
    browserName = "Firefox";
    fullVersion = nAgt.substring(verOffset+8);
    }
    // In most other browsers, "name/version" is at the end of userAgent
    else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) )
    {
    browserName = nAgt.substring(nameOffset,verOffset);
    fullVersion = nAgt.substring(verOffset+1);
    if (browserName.toLowerCase()==browserName.toUpperCase()) {
    browserName = navigator.appName;
    }
    }
    // trim the fullVersion string at semicolon/space if present
    if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix);
    if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix);

    majorVersion = parseInt(''+fullVersion,10);
    if (isNaN(majorVersion)) {
    fullVersion = ''+parseFloat(navigator.appVersion);
    majorVersion = parseInt(navigator.appVersion,10);
    }

    document.write('Browser name = '+browserName+'<br>');
    document.write('Full version = '+fullVersion+'<br>');
    document.write('Major version = '+majorVersion+'<br>');
    document.write('navigator.appName = '+navigator.appName+'<br>');
    document.write('navigator.userAgent = '+navigator.userAgent+'<br>');

    --------------------jQuery change()

    $(function(){
    $("select").change(function () {
    var str = "";
    $("select option:selected").each(function () {
    str += $(this).text() + " ";
    });
    $("#rateCar").text(str);
    })
    .change();
    })

    --------------------CSS only change color

    #myTest ul li:nth-child(3) { color: #fc0; }

    #myTest ul li:last-child{
    color:#F00;
    }

    --------------------jQuery change() highlight selected or checked

    $(function(){ $('#typeBook').change(function(){ $('select option:selected').css('border','1px solid #F00'); //$('select option:checked').css('border','1px solid #F00'); }) })

    --------------------jQuery change location

    $(window).attr('location','http://www.google.com')

    --------------------jQuery change position of element based on another element

    var p = $("p:first"); var position = p.position(); var lftPos = position.left; $("p:nth-child(2)").text("left: " + position.left + ", top: " + position.top); $('#myImage').css('position','relative').css('left', lftPos);

    --------------------basics of ul, li

    .newList ul { margin:auto; padding:0px; } .newList li { list-style:square; float:left; /* display:inline;*/ margin:10px; }

     

    --------------------jQuery find position of mouse

    $(document).mousemove(function(e){
    $('#showResult').html(e.pageX +', '+ e.pageY);
    });

    $("#myElement").click(function(e){
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    $('#showResult').html(x +', '+ y);
    });

     

    --------------------jQuery Center Object in Viewport

    $(function() {
    var viewportWidth = jQuery(window).width();
    var viewportHeight = jQuery(window).height();
    var foo = $('#popOut');
    elWidth = foo.width();
    elHeight = foo.height();
    elOffset = foo.position();
    $(window).scrollTop(elOffset.top + (elHeight * 0.5) - (viewportHeight * 0.5)).scrollLeft(elOffset.left + (elWidth * 0.5) - (viewportWidth * 0.5));
    });

    --------------------javascript fill Bingo card with random numbers (number range limited per column)

    function bingo(){
    for(i = 0; i < 15; i++ ){
    setSquare(i)
    }
    }
    function setSquare(thisSquare){
    var currSquare = 'square' + thisSquare;
    var colPlace = new Array(0,1,2,3,4,0,1,2,3,4,0,1,2,3,4);//this sets limits for the range of number possible in a given column
    var newNum = (colPlace[thisSquare] * 15) + Math.floor(Math.random() * 15) + 1;
    document.getElementById(currSquare).innerHTML = newNum;

    }

    --------------------jQuery switch case example


    $(function(){
    $(':button').click(function(){
    switch(this.value){
    case "Kennedy":
    alert('ask not')
    break;

    case "Nixon":
    alert('not a crook')
    break;

    case "Lincoln":
    alert('4 score');
    break;

    default:
    return false;
    }
    })
    })

    --------------------javascript send content to new window and write content in original window

    function openWin()
    {
    myWindow=window.open('','','width=200,height=100');
    myWindow.document.write("This is 'myWindow'!");
    myWindow.focus();
    myWindow.opener.document.write("<p>This is the source window!</p>");
    }
    </script>

     

    --------------------jQuery add div onClick and display current number

    $('#butt1').click(function(){ $('
    New Div
    ').appendTo('#two'); var divNumber = $("#two > div").size() $('#showResult').text(divNumber); })

    --------------------jQuery simple rotating banner

    $(function(){ var curNum = 0; function rotate(){ curNum ++ ; if(curNum == picArray.length){ curNum = 0; } $('#myImage').attr('src', picArray[curNum]) } setInterval(rotate, 2000); })

    --------------------jQuery open content in window based on class

    $(function(){ $('a').each(function(){ if ($(this).hasClass('newWin')) { $(this).css('color','green') } else{ $(this).css('color','black') } }) $('a').click(function(){ if ($(this).hasClass('newWin')){ var mySite = $(this).attr('href') var siteWindow = window.open(mySite, "siteWin", "width=300, height=600, resizable=0, location=0, left=400,top=20"); siteWindow.focus(); return false;} else{ return false; } }) })

    --------------------jQuery form snippets

    Getting the value of a selected option:
    $('#selectList').val();
    Getting the text/value of multiple selected options:
    var foo = []; $('#multiple :selected').each(function(i, selected){ foo[i] = $(selected).text(); });
    this returns a string or array:
    6 foo = $('#multiple :selected').val();
    Using selected options in conditional statements:
    switch ($('#selectList :selected').text()) { case 'First Option': //do something break; case 'Something Else': // do something else break; }
    Removing an option:
    $("#selectList option[value='2']").remove();
    Moving options from list A to list B:
    $().ready(function() { $('#addButton').click(function() { return !$('#select1 option:selected').appendTo('#select2'); }); $('#removeButton').click(function() { return !$('#select2 option:selected').appendTo('#select1'); }); });

    --------------------jQuery updating list as selections change