Showing posts with label javascript. Show all posts

get head content of page with jquery

by in , 0

You can use this code:
With Jquery


$("head")
//for example:
alert($("head").html());

With JS:

var headContent = document.getElementsByTagName("head")[0].innerHTML;

auto refresh for every 5 mins in Javascript

by in 0

We can do this function with just html  or just javascript

Refresh document every 300 seconds using HTML Meta tag add this inside the head tag of the page
 <meta http-equiv="refresh" content="300">
Or using Java Script:
            setInterval(function() {
                  window.location.reload();
                }, 300000); 

jQuery javascript regex Replace br tag with \n

by in , , 0

var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");
or using jQuery:
var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));
edit: added i flag
edit2: you can use /<br[^>]*>/gi wich will match anything between the br and slash if you have for example <br />

Source:

jQuery javascript regex Replace <br> with \n

disable selected options by jQuery

by in , 0

This will disable/enable the options when you select/remove them, respectively.
$("#theSelect").change(function(){          
    var value = $(this).val();
    if (value === '') return;
    var theDiv = $(".is" + value);

    var option = $("option[value='" + value + "']", this);
    option.attr("disabled","disabled");

    theDiv.slideDown().removeClass("hidden");
    theDiv.find('a').data("option",option);
});


$("div a.remove").click(function () {     
    $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
    $(this).data("option").removeAttr('disabled');
});
Source: 
jQuery - disable selected options

JavaScript QR Code Reader

by in , 0

I'm doing a bit of preliminary research on an upcoming project and I have a quick question that I figure I'll throw up here while I look elsewhere, in case anyone has any experience with this.
The question is simple: is it possible to read a QR code using JavaScript? Is there a remote service to which I can pass a bitmap object from a camera and do it that way? Are there currently any libraries that allow this?
The project is going to be deployed to various mobile devices and we'd like to try to use Appcelerator to make it work. I know Appcelerator does expose the Camera API on its host devices, but whatever we do with it has to be able to parse QR codes. Is this something that can be done?
Thanks in advance!

Read more »

10 Mobile Touch Javascript Frameworks

by in , 0

Mobile development is not an easy job for a developer who doesn’t know about the latest technologies, updates and trends that’s why mobile development is a stressful job. Major challenges a mobile developer faces are screen resolution, cross browser compatibility.
We know many of these issues have been solved as the mobile development industry is growing up. Now, we can see mobile websites with beautiful layouts are being developed. These mobile websites also have touch screen functionality that is developed with the help of different frameworks to work on tablets and smartphones.





Now, folks love to surf websites via their tablets, smartphones etc. So, having a mobile edition of your website is necessary. All this has been possible because of JavaScript, which has developed many frameworks to display our websites on mobile devices smoothly. So, below is the list of my Top 10 Mobile Touch JavaScript Frameworks.

1. pointer.js

pointer.js-
If you want unifying mouse and touch systems, pointer.js is the best tool. pointer.js reinforces pointer-like input models to work on various devices and browsers. You can do multi-touch drawing, gesture event logger and pointer event logger.

Read more »

jquery disable form submit on enter

by in , 0

You can disable button on Submit but user can Enter to submit.

So you i use this code:

I have the following javascript in my page which does not seem to be working.
$('form').bind("keypress", function(e) {
  if (e.keyCode == 13) {               
    e.preventDefault();
    return false;
  }
});
I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit. Either solution is acceptable but the code I'm including above does not prevent the form from submitting.

Solution:

jquery disable form submit on enter


Usually form is submitted on Enter when you have focus on input elements.
We can disable Enter press on input elements within a form:
$("form :input").on("keypress", function(e) {
    return e.keyCode != 13;
});​

javascript replace only first instance .replace?

by in 0

I have this
 var date = $('#Date').val();
this get the value in the textbox what would look like this
12/31/2009
Now I do this on it
var id = 'c_' + date.replace("/", '');
and the result is
c_1231/2009
It misses the last '/' I don't understand why though.

Read more »

Tutorial Word Count Bookmarklet

by in , 0

Add to bookmarks bar, select text, click it to get the word count.

<a href="javascript:(function(){var%20t;if%20(window.getSelection)%20t%20=%20window.getSelection();else%20if%20(document.selection)%20t%20=%20document.selection.createRange();if%20(t.text%20!=%20undefined)%20t%20=%20t.text;if(!t%20||%20t%20==%20""){%20a%20=%20document.getElementsByTagName("textarea");%20for(i=0;%20i<a.length;%20i++)%20{%20%20if(a[i].selectionStart%20!=%20undefined%20&&%20a[i].selectionStart%20!=%20a[i].selectionEnd)%20%20{%20%20%20%20t%20=%20a[i].value.substring(a[i].selectionStart,%20a[i].selectionEnd);%20%20%20%20break;%20%20}%20}}if(!t%20||%20t%20==%20"")alert("please%20select%20some%20text");else%20alert("word%20count:%20"%20+%20t.toString().match(/(\S+)/g).length);})()" class="button">Count Words</a>

Bookmarklet

Count Words < Drag to Bookmarks Bar

Reference URL

Tutorial Viewport Size, Screen Resolution, Mouse Postition

by in , 0

This code is cross-browser compatible and checks the dimensions of the viewport, the screen resolution and the mouseposition which can be quite helpful to perform some checks with JavaScript.

<script type="text/javascript">
function getViewportWidth()
{
       if (window.innerWidth)
       {
               return window.innerWidth;
       }
       else if (document.body && document.body.offsetWidth)
       {
               return document.body.offsetWidth;
       }
       else
       {
               return 0;
       }
}

function getViewportHeight()
{
       if (window.innerHeight)
       {
               return window.innerHeight;
       }
       else if (document.body && document.body.offsetHeight)
       {
               return document.body.offsetHeight;
       }
       else
       {
               return 0;
       }
}

var tellMeTheSizes=function()
{
       document.getElementById("viewportwidth").innerHTML = getViewportWidth() + "px";
       document.getElementById("viewportheight").innerHTML = getViewportHeight() + "px";
       document.getElementById("resolutionheight").innerHTML = screen.height + "px";
       document.getElementById("resolutionwidth").innerHTML = screen.width + "px";
}

window.onload=function()
{
       tellMeTheSizes();
}

window.onresize=function()
{
       tellMeTheSizes();
}

window.onmousemove=function(event)
{
       ev = event || window.event;
       document.getElementById("mousetop").innerHTML = ev.pageY + "px";
       document.getElementById("mouseleft").innerHTML = ev.pageX + "px";
}
</script>

Tutorial Validate HTML Bookmarklet

by in , 0

javascript:(function(){%20function%20fixFileUrl(u)%20{%20var%20windows,u;%20windows%20=%20(navigator.platform.indexOf("Win")%20!=%20-1);%20%20/*%20chop%20off%20file:///,%20unescape%20each%20%hh,%20convert%20/%20to%20\%20and%20|%20to%20:%20*/%20%20u%20=%20u.substr(windows%20?%208%20:%207);%20u%20=%20unescape(u);%20if(windows)%20{%20u%20=%20u.replace(/\//g,"\");%20u%20=%20u.replace(/\|/g,":");%20}%20return%20u;%20}%20/*%20bookmarklet%20body%20*/%20var%20loc,fileloc;%20loc%20=%20document.location.href;%20if%20(loc.length%20>%209%20&&%20loc.substr(0,8)=="file:///")%20{%20fileloc%20=%20fixFileUrl(loc);%20if%20(prompt("Copy%20filename%20to%20clipboard,%20press%20enter,%20paste%20into%20validator%20form",%20fileloc)%20!=%20null)%20{%20document.location.href%20=%20"http://validator.w3.org/file-upload.html"%20}%20}%20else%20document.location.href%20=%20"http://validator.w3.org/check?uri="%20+%20escape(document.location.href);%20void(0);%20})();

Make a bookmark with the above code, or just drag the following button link to your bookmarklets bar.

validate html

Tutorial Unescape HTML in JS

by in , 0

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

Usage

htmlDecode("&lt;img src='myimage.jpg'&gt;"); 
// returns "<img src='myimage.jpg'>"

Tutorial Trim First/Last Characters in String

by in , 0

Remove last four characters

var myString = "abcdefg";
var newString = myString.substr(0, myString.length-4); 
// newString is now "abc"

Remove first two characters

var myString = "abcdefg";
var newString = myString.substr(2);
// newString is now "cdefg"

Notes

The substr function can be called on any string with two integer parameters, the second optional. If only one provided, it starts at that integer and moves to the end of the string, chopping off the start. If two parameters provided, it starts at the first number and ends at the second, chopping off the start and end as it is able.

Example

abcdefghijklmnopqrstuvwxyz

Press to Chop

Tutorial Toggle (Show/Hide) Element

by in , 0

<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>

Inline usage:

<a href="#" >Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>

Reference URL

Tutorial Test if Mac or PC with JavaScript

by in , 0

User Agent testing sucks, but sometimes you need it for subtle things. In my case I was using it to adjust what I was showing for keyboard shortcut keys (Command or Control). Nothing super major.

if (navigator.userAgent.indexOf('Mac OS X') != -1) {
  $("body").addClass("mac");
} else {
  $("body").addClass("pc");
}

The statements in there use jQuery to add a body class, but that's not required, you could do whatever.

Tutorial Test if Element Supports Attribute

by in , 0

Not all browsers support all attributes on all elements. There are a number of new attributes in HTML5, so the idea of testing to see what kind of browser environment you are in becomes every increasingly important.

function elementSupportsAttribute(element, attribute) {
  var test = document.createElement(element);
  if (attribute in test) {
    return true;
  } else {
    return false;
  }
};

Usage

if (elementSupportsAttribute("textarea", "placeholder") {

} else {
   // fallback
}

Tutorial Test if dragenter/dragover Event Contains Files

by in , 0

HTML5 drag and drop is great for handling file uploads. But if that's the only thing you are using it for, it's nice to know if any particular dragenter or dragover event actually has files. Unlike, for example, just the dragging of some selected text.

Send the event object to this function and it will return the truth (assuming you are in a browser that supports all this):

function containsFiles(event) {

    if (event.dataTransfer.types) {
        for (var i = 0; i < event.dataTransfer.types.length; i++) {
            if (event.dataTransfer.types[i] == "Files") {
                return true;
            }
        }
    }
    
    return false;

}

Reference URL

Tutorial Test for Internet Explorer in JavaScript

by in , 0

var isMSIE = /*@cc_on!@*/0;

if (isMSIE) {
  // do IE-specific things
} else {
  // do non IE-specific things
}

Reference URL

Tutorial Support Tabs in Textareas

by in , 0

Normally the tab key moves to the next focusable thing. This inserts a tab character in instead.

HTMLTextAreaElement.prototype.getCaretPosition = function () { //return the caret position of the textarea
    return this.selectionStart;
};
HTMLTextAreaElement.prototype.setCaretPosition = function (position) { //change the caret position of the textarea
    this.selectionStart = position;
    this.selectionEnd = position;
    this.focus();
};
HTMLTextAreaElement.prototype.hasSelection = function () { //if the textarea has selection then return true
    if (this.selectionStart == this.selectionEnd) {
        return false;
    } else {
        return true;
    }
};
HTMLTextAreaElement.prototype.getSelectedText = function () { //return the selection text
    return this.value.substring(this.selectionStart, this.selectionEnd);
};
HTMLTextAreaElement.prototype.setSelection = function (start, end) { //change the selection area of the textarea
    this.selectionStart = start;
    this.selectionEnd = end;
    this.focus();
};

var textarea = document.getElementsByTagName('textarea')[0]; 

textarea.onkeydown = function(event) {
    
    //support tab on textarea
    if (event.keyCode == 9) { //tab was pressed
        var newCaretPosition;
        newCaretPosition = textarea.getCaretPosition() + "    ".length;
        textarea.value = textarea.value.substring(0, textarea.getCaretPosition()) + "    " + textarea.value.substring(textarea.getCaretPosition(), textarea.value.length);
        textarea.setCaretPosition(newCaretPosition);
        return false;
    }
    if(event.keyCode == 8){ //backspace
        if (textarea.value.substring(textarea.getCaretPosition() - 4, textarea.getCaretPosition()) == "    ") { //it's a tab space
            var newCaretPosition;
            newCaretPosition = textarea.getCaretPosition() - 3;
            textarea.value = textarea.value.substring(0, textarea.getCaretPosition() - 3) + textarea.value.substring(textarea.getCaretPosition(), textarea.value.length);
            textarea.setCaretPosition(newCaretPosition);
        }
    }
    if(event.keyCode == 37){ //left arrow
        var newCaretPosition;
        if (textarea.value.substring(textarea.getCaretPosition() - 4, textarea.getCaretPosition()) == "    ") { //it's a tab space
            newCaretPosition = textarea.getCaretPosition() - 3;
            textarea.setCaretPosition(newCaretPosition);
        }    
    }
    if(event.keyCode == 39){ //right arrow
        var newCaretPosition;
        if (textarea.value.substring(textarea.getCaretPosition() + 4, textarea.getCaretPosition()) == "    ") { //it's a tab space
            newCaretPosition = textarea.getCaretPosition() + 3;
            textarea.setCaretPosition(newCaretPosition);
        }
    } 
}

Reference URL

Tutorial Strip Whitespace From String

by in , 0

Whitespace, meaning tabs and spaces.

// Remove leading and trailing whitespace
// Requires jQuery
var str = " a b    c d e f g ";
var newStr = $.trim(str);
// "a b c d e f g"

// Remove leading and trailing whitespace
// JavaScript RegEx
var str = "   a b    c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "a b c d e f g"

// Remove all whitespace
// JavaScript RegEx
var str = " a b    c d e   f g   ";
var newStr = str.replace(/\s+/g, '');
// "abcdefg"

Doesn't work with other types of whitespace though, for instance &#8239; (thin space) or &nbsp; (non-breaking space)