Archive for the ‘javascript’ Category

How to disable default drag and drop behaviour

There’s a feature of browsers that allows to drag and drop elements such as links, images, etc. Sometimes this behaviour may be undesirable, for example, when you’re implementing your own special drag and drop. In this short note I’ll provide a small JavaScript code snippets that prevent a default drag and drop behaviour.

The following code snippet will disable a default drag and drop behaviour for all the elements:

  $(document).bind("dragstart", function(event) {
    event.preventDefault();
  });

This code snippet prevents default drag and drop behaviour only for hyperlinks:

  $(document).bind("dragstart", function(event) {
    if (event.target.tagName.toLowerCase() === "a") {
      event.preventDefault();
    }
  });

You can try it here http://jsfiddle.net/v5E6n/1/.

Input file change event

Using a JavaScript you can process changes when user selects some files via input file. You can do this with help of change event.

It’s a short tip about change event of input of type file. I’ve recently looked for this event and it’s hard to gether that information fast. So, firstly, it’s a tip for myself and maybe it’ll be useful for others.

<form>
  <input type="file" multiple> 
  <input type="submit"> 
</form>

onchange

Occurs when a file or files have been selected in the dialog.

If the same files selected again the event isn’t fired.

In some browsers, Google Chrome for example, it occurs when you click “Cancel” in the dialog and the value is cleared. In FireFox, the event isn’t occured when “Cancel” is presssed and the value isn’t cleared. So, to clear the value of the input file you need to add another button that resets a value and this approach will work in all the browsers.

Here’s a simple jQuery example:

1
2
3
  $("[type='file']").bind("change", function () {
    alert("You've selected " + this.files + " files!");
  });

Also, it’s possible to trigger change event if you want:

  $("[type='file']").trigger("change");

oninput

It seems that input event works identically to change event. I haven’t tested yet.

Script that positions html element over YouTube video

In the previous article we discussed how to position HTML elements over YouTube video. The problem is that YouTube video overlaps any html element, by default. How to force YouTube video showing behind HTML elements with help of HTML approach read in following article How to position html elements over YouTube video.

Here you’ll see how to perform the same but with JavaScript approach. First, script finds all the YouTube iframes and then adds wmode parameter to them. This wmode parameter should have transparent or opaque values.

1
2
3
4
5
  jQuery(function ($) {
    $("iframe[src]").each(function () {
      $(this).prop("src", $(this).prop("src") + "?wmode=transparent");
    });
  });

In this script jQuery of 1.8.2 is used. Note that this fix is needed for old browsers, for example, IE9 and older, some verstions of FireFox.

cssRules null in Chrome

I found this problem when tryed to use cssRules of document.styleSheets[i] locally in Chrome but found that cssRules is null and only in Chrome. I need only to add some rules but not to read or modify existed rules so this fix is not for all.

Here’s the bug .

And here’s my workaround for this problem:

var styles = document.styleSheets;
var style = null;
for (var s = 0; s < styles.length; s++)
    if(!styles[s].href) {
        style = styles[s];
        break;
    }
if (style == null)
    style = jQuery("text/css\">")
        .appendTo('head').get(0);
var rules = style.cssRules; // is not null!!!

Accessing a dimensional array in JavaScript

Let’s declare a two dimensional array and try to access the element. Here is the first example:

var array = [[1, 2, 3],[4, 5, 6]];
alert(array[1][1]);
// Output: 5

Here is the same sample but with another sytnax:

var array = new Array(2);
array[0] = new Array(3);
array[0][0] = 1;
array[0][1] = 2;
array[0][2] = 3;
array[1] = new Array(3);
array[1][0] = 4;
array[1][1] = 5;
array[1][2] = 6;
alert(array[1][1]);
// Output: 5

Again, another syntax of this example to access a javascript array:

var array = new Array(new Array(1, 2, 3), new Array(4, 5, 6));
alert(array[1][1]);
// Output: 5

Some developers make the following error when accessing a JavaScript array and wait that the 5 will be returned:

var array = [[1, 2, 3],[4, 5, 6]];
alert(array[1,1]);
// Output: [4, 5, 6]

JavaScript interpretes 1,1 as a comma separated expression and this expression returnes 1. Each part of the comma separated expression is executed left to right. The final value of the comma separated expression is the value of the last comma part. So, when you try to evaluate the following script in the sample below you will get the last array item because the value of the comma separated expression 0,1,2 will be 2:

var array = [1, 2, 3];
alert(array[0,1,2]);
// Output: 3

How to test for an empty javascript object

Hi everybody! I’ve just had a discussion of how to test for an emtpy javascript object. As a result, I have several code snippets and I want to share them.

Problem

1
2
3
4
5
6
7
  alert({} == null); // false
  alert({} == {}); // false
  alert({} == {}); // false
  alert({} == 0); // false
  alert({} == ""); // false
  alert({} == []); // false
  // etc :)

So, none of the expressions above can check for an empty javascript object.

Pure javascript solution

1
2
3
4
5
6
7
  function empty(o) {
    for(var i in o) 
      if(o.hasOwnProperty(i))
        return false;
 
      return true;
  }
object.hasOwnProperty(property) Returns a boolean indicating whether the object has the specified property. This method does not check down the object’s prototype chain.

Learn details of hasOwnProperty here at developer.mozilla.org.

JQuery + JQuery.JSON solution

1
2
3
4
5
  var o = {};
  alert($.toJSON(o) == '{}'); // true
 
  var o = {a: 1};
  alert($.toJSON(o) == '{}'); // false

The code above simply converts an object to JSON string.

UPDATE: jQuery.isEmptyObject method

As of jQuery 1.4, there’s isEmptyObject method to detect is the object empty. Look at the followtin code for example:

1
2
  $.isEmptyObject({}); // true
  $.isEmptyObject({someprop: "true"}); // false

Your way

Well, if you have your way of checking for an empty javascript object I am waiting your comments! Thanks in advance!

Links

jQuery.isEmptyObject

hasOwnProperty documentation

JQuery JavaScript Library