you are here: codestackercodes [RSS] → tag javascript [RSS]

getElementByClassName

function getElementsByClassName(node,classname) {
  if (node.getElementsByClassName) { // use native implementation if available

    return node.getElementsByClassName(classname);
  } else {
    return (function getElementsByClass(searchClass,node) {
        if ( node == null )
          node = document;
        var classElements = [],
            els = node.getElementsByTagName("*"),
            elsLen = els.length,
            pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

        for (i = 0, j = 0; i < elsLen; i++) {
          if ( pattern.test(els[i].className) ) {
              classElements[j] = els[i];
              j++;
          }
        }
        return classElements;
    })(classname, node);
  }
}

var elements = getElementsByClassName(document, "myclass"); // example

detecting popup blockers

var win = window.open(...);
if(win == null || typeof(win) == "undefined" || (win == null && win.outerWidth == 0) || (win != null && win.outerHeight == 0) || win.test == "undefined") {
// popup blocked :(

}

simple date validation

function dateValidation() {

	var obj = document.getElementById("my_field"); // my_field: 12/12/2011

	var day = obj.value.split("/")[0];

	var month = obj.value.split("/")[1];
	var year = obj.value.split("/")[2];

	if ((day<1 || day >31) || (month<1&&month>12)&&(year.length != 4)) {
		alert("Invalid format");
		return false;
	} else {

		var dt = new Date(year, month-1, day);
		var today = new Date();

		if((dt.getDate() != day) || (dt.getMonth() != month-1) || (dt.getFullYear()!=year) || (dt>today)) {
			alert("Invalid date");
			return false;
		}
	}
}

reserved javascript words

break
case
catch
continue
default
delete
do
else
finally
for
function
if
in
instanceof
new
return
switch
this
throw
try
typeof
var
void
while
with
abstract
boolean
byte
char
class
const
debugger
double
enum
export
extends
final
float
goto
implements
import
int
interface
long
native
package
private
protected
public
short
static
super
synchronized
throws
transient
volatile

reading rss with google feeds

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">

google.load("feeds", "1");

function initialize() {
  var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
  feed.load(function(result) {
    if (!result.error) {
      var container = document.getElementById("feed");
      for (var i = 0; i < result.feed.entries.length; i++) {
        var entry = result.feed.entries[i];
        var div = document.createElement("div");
        div.appendChild(document.createTextNode(entry.title));
        container.appendChild(div);
      }
    }
  });
}
google.setOnLoadCallback(initialize);

</script>
<div id="feed"></div>

detecting iDevices

if (navigator.userAgent.match(/iP(ad|hone|od)/i)) {
 
// hello!


}

rails inspired helpers in javascript

var link_to = function (text, url, options) {
  var link = document.createElement('a');
  link.textContent = text;
  link.setAttribute('href', url);

  for (option in options) {
    link.setAttribute(option, options[option]);
  }

  return link;
};

var image_tag = function (alt, src, options) {
  var image = document.createElement('img');
  image.setAttribute('alt', alt);
  image.setAttribute('src', src);

  for (option in options) {
    image.setAttribute(option, options[option]);
  }

  return image;
};

link_to("Google", "http://google.com", { id: 321, title: "Google" });

image_tag("Google", "http://www.google.com/images/logos/ps_logo2.png", { id: "logo", title: "Google's Logo" });

detecting webkit

if (/webkit/.test(navigator.userAgent.toLowerCase())) {
	alert('hello webkit!');
}

easiest tooltip ever

based on http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery version

<style>
	#tooltip {
		position:absolute;
		border:1px solid #333;
		background:#f7f5d1;
		padding:2px 5px;
		color:#333;
		display:none;
	}
</style>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript">
	$(document).ready(function(){			
	    xOffset = 10;
		yOffset = 20;				

		$("a.tooltip").hover(function(e){											  
			this.t = this.title;
			this.title = "";									  
			$("body").append("<p id='tooltip'>"+ this.t +"</p>");
			$("#tooltip").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px").fadeIn("fast");		
	    }, function(){
			this.title = this.t;
			$("#tooltip").remove();
	    });	

		$("a.tooltip").mousemove(function(e){
			$("#tooltip").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px");
		});
	});
</script>

<a href="http://cssglobe.com" class="tooltip" title="Web Standards Magazine">Roll over for tooltip</a>

resize browser

$(document).ready(function(){

$(window).bind("resize", resizeWindow);
function resizeWindow( e ) {
	var newWindowHeight = $(window).height();
	$("#container").css("min-height", newWindowHeight );
}

});

dynamic js loading

<html>
<head>
<title>Dynamic JavaScript Loading</title>
<script type="text/javascript">
function loadJS(src){
  var js = document.createElement('script');
  js.setAttribute('type','text/javascript');
  js.setAttribute('src', src);
  document.body.appendChild(js);
}
</script>
</head>
<body>
<a href="javascript:loadJS('dynamic.js');">Load JavaScript</a>
</body>

gerador de cpf

<script language="JavaScript">

// Função para gerar números randômicos

function gera_random(n)
{
    var ranNum = Math.round(Math.random()*n);
    return ranNum;
}

// Função para retornar o resto da divisao entre números (mod)

function mod(dividendo,divisor) 
{
	return Math.round(dividendo - (Math.floor(dividendo/divisor)*divisor));
}

// Função que gera números de CPF válidos

function cpf()
{
	var n = 9;
	var n1 = gera_random(n);
 	var n2 = gera_random(n);
 	var n3 = gera_random(n);
 	var n4 = gera_random(n);
 	var n5 = gera_random(n);
 	var n6 = gera_random(n);
 	var n7 = gera_random(n);
 	var n8 = gera_random(n);
 	var n9 = gera_random(n);
 	var d1 = n9*2+n8*3+n7*4+n6*5+n5*6+n4*7+n3*8+n2*9+n1*10;
 	d1 = 11 - ( mod(d1,11) );
 	if (d1>=10) d1 = 0;
 	var d2 = d1*2+n9*3+n8*4+n7*5+n6*6+n5*7+n4*8+n3*9+n2*10+n1*11;
 	d2 = 11 - ( mod(d2,11) );
 	if (d2>=10) d2 = 0;
 	return ''+n1+n2+n3+'.'+n4+n5+n6+'.'+n7+n8+n9+'-'+d1+d2;
}

// Função que gera números de CNPJ válidos

function cnpj()
{
	var n = 9;
	var n1  = gera_random(n);
 	var n2  = gera_random(n);
 	var n3  = gera_random(n);
 	var n4  = gera_random(n);
 	var n5  = gera_random(n);
 	var n6  = gera_random(n);
 	var n7  = gera_random(n);
 	var n8  = gera_random(n);
 	var n9  = 0;//gera_random(n);

 	var n10 = 0;//gera_random(n);

 	var n11 = 0;//gera_random(n);	

 	var n12 = 1;//gera_random(n);		

	var d1 = n12*2+n11*3+n10*4+n9*5+n8*6+n7*7+n6*8+n5*9+n4*2+n3*3+n2*4+n1*5;
 	d1 = 11 - ( mod(d1,11) );
 	if (d1>=10) d1 = 0;
 	var d2 = d1*2+n12*3+n11*4+n10*5+n9*6+n8*7+n7*8+n6*9+n5*2+n4*3+n3*4+n2*5+n1*6;
 	d2 = 11 - ( mod(d2,11) );
 	if (d2>=10) d2 = 0;
 	return ''+n1+n2+'.'+n3+n4+n5+'.'+n6+n7+n8+'/'+n9+n10+n11+n12+'-'+d1+d2;
}

// Função para escolher qual função chamar de acordo com a chamada

function faz()
{
	if (document.form1.tipo[0].checked)
		document.form1.numero.value = cpf();
	else
		document.form1.numero.value = cnpj();
}

// FIM

</script>

<form name="form1" method="POST" action=""> 
<strong>Gerador de CPF e CNPJ</strong><br/>
<input name="numero" type="text" id="numero" size="20" style="color: #808080; border: 1px solid #000000; "><br/>
<input name="tipo" type="radio" value="cpf" checked> CPF 
<input type="radio" name="tipo" value="cnpj"> CNPJ <br/>
<input type="button" name="Button" value="Gerar" onClick="faz()" />

</form>

fetching tweets with jquery

$(document).ready(function() {
    // Declare variables to hold twitter API url and user name

    var twitter_api_url = 'http://search.twitter.com/search.json';
    var twitter_user    = 'leozera';

    // Enable caching

    $.ajaxSetup({ cache: true });

    // Send JSON request

    // The returned JSON object will have a property called "results" where we find

    // a list of the tweets matching our request query

    $.getJSON(
        twitter_api_url + '?callback=?&rpp=5&q=from:' + twitter_user,
        function(data) {
            $.each(data.results, function(i, tweet) {
                // Uncomment line below to show tweet data in Fire Bug console

                // Very helpful to find out what is available in the tweet objects

                //console.log(tweet);


                // Before we continue we check that we got data

                if(tweet.text !== undefined) {
                    // Calculate how many hours ago was the tweet posted

                    var date_tweet = new Date(tweet.created_at);
                    var date_now   = new Date();
                    var date_diff  = date_now - date_tweet;
                    var hours      = Math.round(date_diff/(1000*60*60));

                    // Build the html string for the current tweet

                    var tweet_html = '<div class="tweet_text">';
                    tweet_html    += '<a href="http://www.twitter.com/';
                    tweet_html    += twitter_user + '/status/' + tweet.id + '">';
                    tweet_html    += tweet.text + '<\/a><\/div>';
                    tweet_html    += '<div class="tweet_hours">' + hours;
                    tweet_html    += ' hours ago<\/div>';

                    // Append html string to tweet_container div

                    $('#tweet_container').append(tweet_html);
                }
            });
        }
    );
});

smooth scrolling with jquery

// Smooth scrolling within page anchors

$('a[href*=#]').click(function() {
    
  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        
        var $target = $(this.hash);
            
        $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            
        if ($target.length) {
              var targetOffset = $target.offset().top;
              $('html,body').animate({scrollTop: targetOffset}, 1000);
              return false;       
        }      
     }        
});

clean way to open a popup window

$('a.popup').live('click', function(){
	newwindow=window.open($(this).attr('href'),'','height=200,width=150');
	if (window.focus) {newwindow.focus()}
	return false;
});

seletores do jquery

http://docs.jQuery.com/DOM/Traversing/Selectors

$('h1') // elementos h1

$('#meuID') // elementos com id "meuID"

$('.minhaClasse') // elementos definidos com a classe "minhaClasse"

$('[width]') // elementos que possuem o atributo width definido

$('[width=500]') // elementos que possuem o atributo width definido como 500

$('img[width=300]') // imagens que possuem largura = 300

$('img[src$=png]') // imagens com final png

$('a[href^=http://localhost]') // links que comecem com http://localhost

$('a[href$=pdf]') // links com final pdf

$('a[href*=www]') // links que contém www

$(':empty') // elementos vazio

$('div:empty') // elementos div vazios

$(':has(p)') // todos elementos que tenham um parágrafo

$('div:has(a)'); // elementos div que possuem link

$("p:contains('dinei')") // parágrafos que contém a palavra "dinei"

$("p:eq(0)") // seleciona o primeiro elemento p

copy to clipboard

function copyToClipBoard(id) {
    Copied = document.getElementById('id').innerText.createTextRange();
    Copied.execCommand("Copy");
}

back to top

<a href="#top" onclick="$('html, body').animate({scrollTop:0}, 'slow'); return false;">top</a>

unobstrusive popup

http://www.quirksmode.org/js/popup.html

   function popup(url) {
        newWindow = window.open(url, 'name', 'height=400,width=335,scrollbars=yes');
        if (window.focus) { newWindow.focus() }
            return false;
    }

// <a href="link.html" onclick="popup('link.html');">Link</a>

hide/show dl list with jquery

		$(document).ready(function() {
			$('dd').toggle();
			$('dt').click(function() {$(this).next('dd').toggle('slideDown');});
		});
Displaying Code 1 - 20 of 40 in total