Archive for the ‘JavaScript’ category

Javascript: Object Detection or Browser Detection?

November 21st, 2009

This question can be answered easily with “object detection” – why? Because some obscure browsers won’t be treated correctly and browsers that appear after you’ve written the page may not be adequately covered either as a result you will end up with some error in some browsers. Object detection works fairly in all browsers.

But, certain features of Javascript don’t work in all browsers. As an example “innerText” property doesn’t work in Firefox but in IE, Chrome Etc…this problem could be solved easily like the following ..

var text = x.innerText || x.textContent
//innerText for IE or other browsers and textContent for Firefox that works well.

Now, consider the following statement

Google Chrome doesn’t read encoding information that’s declared with document.write(). If you’re using this method to declare encoding in iframes, for example, you may see garbled characters when the iframe is rendered. Instead of:

document.write("<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">");
    ... other JavaScript code ...
</meta>

and when it might arrived? Let’s say you are using a Rich Text Editor where you will have onload events with document.write() and you will notice that iframe attribute (e.g name) value is not getting in the browser. Rather Chrome is setting name attrribute value from itself.

There is a tricky way to get it solved, in my case I used Firebug extension to get the attribute value and then detect the browser. Well in that case object detection doesn’t work for me. I must use browser detection right.

Let’s have a look at the following codes to get some idea about what I have been talking…

function notEmpty(){
 
        var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
        var textvalue = '';
        var framename = '';
        var elementValue = ''; 
 
        if(is_chrome) {
            elementValue = window.frames['Rich text editor'].document.body.innerText;
        }
        else if(navigator.appName =="Microsoft Internet Explorer") {
            elementValue = window.frames['myIframe'].document.body.innterText;
        }
        else {
            elementValue = window.frames['myIframe'].document.body.textContent;
        }
 
        if(elementValue =='')
        {
            //do what you want
            return false;
        }    
        return true;
    }

Conclution: It depends, generally it’s always good to use object detection no doubt. But when you have no option? Well then don’t wait to use browser detection eh… ;)

Check IFRAME Text by Javascript

November 20th, 2009

Most of the Rich Text Editor use iframe, and besides server side validation it’s necessary to check client side validation with JS before storing any data. Let’s say you want to check if the body of iframe is empty. This is a little bit tricky, like you can easily check a textarea value with document.getElementById(idoftextarea).value; but it won’t work in case of iframe. Let’s consider the following scenario…

<iframe name="richEditorIframe" width="100%" height="25%" src="test1.txt">
</iframe>
 
<form name="formName">
     <textarea name="textarea" cols=80 rows=18 id="textArea">
         This is a test
     </textarea>
      <br />
      <button type="submit" value="Submit" />
</form>

Now, to check if iframe is getting in Database with empty value we can make a function like the following….

<script type="'text/javascript'">
    function checkEmpty(){
        var elementValue = window.frames['richEditorIframe'].document.body.innerText;
        if(elementValue=='')
        {
            //say something here
            return false;
        }
        return true;
    }
</script>

instead of innerText you can use innerHTML but then in most of the Text Editor it will show some HTML element which means you are not getting empty result even if you didn’t write anything. So, innerText will give you the iframe body value if it’s written. Now let’s call this function onSubmit in the form…

<form name="formName" onSubmit="return checkEmpty();">
      <textarea name="textarea" cols=80 rows=18 id="textArea">
          This is a test
       </textarea>
       <br />
      <button type="submit" value="Submit" />
</form>

That’s it, now it’s simple :)

Tweet Something from Your Website Using bitly REST Api

June 23rd, 2009

Oho, did I actually write the right title of this post? Bit.ly is not for tweeting, it’s for shortening the long URLs right, but hey, why bit.ly is so popular now? Most common answer could be twitter. I don’t know if people would used this service that much if there wasn’t twitter. Anyways, this is very important to shortening something in your tweet as twitter has character limits. So let’s see how we can actually tweet something from a website using this REST based Api method calls.

Note one thing that if your site is using wordpress or any kind of CMS that allows to use plug-ins then you don’t have to worry about it. This is something you can use only for updating some content to twitter from your site. Hope I made it clear at first….

After digging bitly apis, I think its pretty easy to do it as bitly provides Javascript client library so there shouldn’t be any varier about back-end language. So let’s see how easily we can tweet some content from our site.

First of all, if you redirect anything with the following URL, twitter will get your message in the text box and all you have to do is, just press the update button.

http://twitter.com/home?status=your_message_comes_here

So our message has to be customized and you cannot allow anybody to send message more than 140 chars right. This is why we will use bitly api to customized it.

First of all, we have to add the API library with the following format.

<script type="text/javascript" charset="utf-8" src="http://bit.ly/javascript-api.js?version=latest&login=junal&apiKey=R_888fefa724b856672a3276a3905d8e30"></script>

you need to login to get user name and password from bitly, though you can use demo user name and apikey from here but later you have to use your own authentication information.

Anyways, we are done connecting with bitly by including their JS client library. Now let’s create some functions of our own to call them. Open a JS file and paste the following there, you can find this example codes in the bitly documentation.

var TweetAndTrack = {};
TweetAndTrack.open = function(targ, url) {
var callback_name = url.replace(/\W/g, '');
BitlyClient.call('shorten', {
'longUrl': url,
'history': '1'
}, 'BitlyCB.' + callback_name);
return false;
};
 
TweetAndTrack.popResult = function(data) {
// Results are keyed by longUrl, so we need to grab the first one.
for (var r in data.results) {
return data.results[r];
 }
};

now it’s time to create our own function to call. Here is the example one…

function tweetMe(msg, url) {
var textMessage = msg.replace(new RegExp("^(.{0," + 80 + "}\\b).*"), "$1");
var callback_name = url.replace(/\W/g, '');
BitlyCB[callback_name] = function(data) {
var result = TweetAndTrack.popResult(data);
var tweet_url = "http://twitter.com/home?status=" + encodeURIComponent(textMessage+ "... " + result.shortUrl );
window.open(tweet_url);
};
 
BitlyClient.call('shorten', {
'longUrl': url,
'history': '1'
}, 'BitlyCB.' + callback_name);
 
return false;
}

I have used regular expression here to truncate the message. I kept the length of the message 80! why? Because, your URL will take some chars as well and you should also keep some space for people who will retweet your tweet :)

Now, we have to call this javascript function called “tweetMe()” and it has 2 params right. We have to pass the message and the url along with the message and bit.ly api will make sure that whatever we are sending, it will be customized before sending. So how can we call this function?

<a href=”#” onclick=”return tweetMe(‘Content or message of your tweet‘, ‘URL of your along with your message‘);”>tweet this </a>

Ok, now just click on “tweet this” and then you it will take you to the twitter heaven. Be happy there, and ask me any questions if you can’t reach there ;)

jQuery Time Picker UI

November 14th, 2008

Today, I went through this nice jQuery time picker UI which allows picking the time after clicking in the input box. 24h and 12h formats are available to select.

jQuery Time Picker UI

jQuery Time Picker UI

Got them down and played with it for a while. Must say it’s really fast, you just have to mouse over and select the time. 24h format didn’t have any prefix “AM/PM” but as usual there are prefix for 12h format. One thing is, when it shows the prefix, it goes out of the input box as a result you can only see half of “a” or “p”. So went through the codes and just added a simple CSS class just for this 12h format so that when someone select 12h formats it shows the prefix fully.

Here are some modifications.

CSS (styles.css)
.width80 {
width:80px !important;
}

Now go to the index.html and in line# 233 add the following line ….

$('#demo-4').addClass('width80');

If you use basic 12h format too, then add another line in 234

$('#demo-2').addClass('width80');

That’s it! Now it looks better I guess.

See the full prefix

Full prefix view

You can download the source code from here.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes