Archive

Archive for the ‘jQuery’ Category

easiest jQuery image preview (on select)

July 30th, 2010 dwright No comments

problem space:
You have a select list of images (as urls, or can access the url through an
id, or some such way). When you select a new image you want to see the image
'previewed'.

<script type="text/javascript">
  jQuery(document).ready(function() {
    $('#images_link').change(function(){
      var img_url = $('#images_link :selected').text();
      $('#preview_image').html('<p><img src="'+img_url+'"/></p>');
      $('#preview_image').dialog();
    });
  });
</script> 

<body>
  <label for="images_link">Image</label><br />
    <select id="images_link" name="images[link]">
      <option value=""></option>
      <option value="1">http://example.com/images/foo.png</option>
      <option value="2">http://example.com/images/bar.png</option>
      <option value="3">http://example.com/images/baz.png</option>
    </select>

 <div id='preview_image'><p></p></div>
</body>
Categories: jQuery Tags:

easiest jquery hover image re-sizer

July 27th, 2010 dwright No comments

problem space:
you have some images on an html page which display as 'thumbnails' (i.e reduced size images), when you hover over them with a mouse, you want them to expand to full size (or larger, anyway).

For this example, pretend you are one of those lazy people who does not want to make a smaller 'thumbnail' image for every image you have (hey, it happens ;) (although, I think there are some online services which can do this [generate thumbnails on the fly] in real time now)

So, anyway, you cheat by using the full size image and setting a height and width smaller values

<html>
<head>
<script type="text/javascript">
  jQuery(document).ready(function() {
    $(".img-frame").hover(
      function() {
        $(this).removeAttr('width');
        $(this).removeAttr('height');
      },
      function () {
        $(this).attr("width", 50);
        $(this).attr("height",  50);
      }
    );
  });
</script>
</head>

<body>
<img src="foo.png" height="50px" width="50px" class="img-frame"/>
<img src="bar.png" height="50px" width="50px" class="img-frame"/>
<img src="baz.png" height="50px" width="50px" class="img-frame"/>
</body>
</html>

I think the above is self-explanatory, but I will give a synopsis anyway.

When you 'hover' (mouseover) an image with the 'img-frame' class set, the width and height attributes are removed, the image will display at full size, when you 'mouseoff' the image, the height and width are restored to their original value.

there are many variations you could do here, you could limit the hover size,
(instead of $(this).removeAttr('width');, you could use $(this).attr("width", 200);) for example

Categories: jQuery Tags:

jQuery, containing div, get id’s for all children

June 22nd, 2010 dwright No comments

problem space:
use jQuery to find all the (child) div's (id) within a containing div.

html:

<div class="top">
  <!-- dynamically generated div's -->
  <div id="7_status_854_5234"></div>
  <div id="54_status_54_5234"></div>
  <div id="23_status_27_5234"></div>
</div>

jQuery:

//get all children's div id
var children_ids = [];
$("div.top").contents().filter(
  function(){
    if (this.nodeType == 1) { // nodeType 1 => div
      // reg exp matches div
      var child_ids = this.id.match(/(\d+)_status_\d+_\d+/);
        try {
          children_ids.push(child_ids[1]);
        } catch(e){}
    }
  }
);

$.each(children_ids,  function(i,j){
  console.log(j);
});

// or maybe the more familiar, the non-jquery way
for(var i = 0 ; i < children_ids.length; i++){
  console.log(children_ids[i]);
}
Categories: jQuery Tags:

jQuery post (params) checkbox value even when unchecked

June 18th, 2010 dwright No comments

Problem space:
So, it's an (annoying) fact that html form element checkbox's only send their name=value pairs when they are checked, when they are not checked they don't send anything. (yes, really)

I think of checkbox's as bool's (true/false - on/off) so this is not the behavior I would expect.
There are several 'kludges' around this, many folks just add a hidden field with the same name as the checkbox (often dynamically generated) if the value is 'off'. (you can do a search for that solution).

Here is yet another approach, using jQuery, this does the same thing, but dynamically at submit time.

pros: less annoying than adding a hidden element for every checkbox
cons: slightly obfuscated, can silently fail leading to hard to decipher bugs

<script type="text/javascript" charset="utf-8">
    // do when submit is pressed
    $('form').submit(function() {
      var elements = this.elements;
      for (i=0; i < elements.length; i++) {
        // make sure checkboxes are in POST params even when 'off'
        if (elements[i].type == 'checkbox') {
          if (! $('#'+elements[i].id).is(':checked')) {
            var add_hidden_on_checkbox_off = $("<input>").attr("type",
                        "hidden").attr("name", elements[i].name).val("off");
            $('form').append($(add_hidden_on_checkbox_off));
          }
        }
       }
      //return false; // will not submit form, use to test with
    });
</script>

The above will send all checkbox's when the form is submitted, checked boxes will have the value 'on', unchecked boxes will have the value 'off'.

Side Note:
Originally I had:
if (elements[i].type == 'checkbox' && elements[i].value != 'on') {
but Firefox [3.6.3](Gecko) and Chrome [5.0.375.70](Webkit) handle this value differently.

Firefox will return 'on' whether the checkbox is checked or not, Chrome will return 'on' if the checkbox is checked and nothing if unchecked.

jquery http html form post

January 25th, 2010 dwright No comments

Problem Space:

You are submitting a html form, which contains many (hidden) form elements that you do not want (or need) sent to the server for processing.

<script type="text/javascript"> 

// do when submit is pressed
// don't send the 'hidden' textarea content
//  its' un-needed and clutters up the post (and wastes bandwidth)
$('form').submit(function() {

  var elements = this.elements;

  for (i=0; i < elements.length; i++) {

    // if textarea id ends in ".tmpl", exclude from post
    if (elements[i].id && elements[i].id.match(/\.tmpl$/)) {

      // could change the val,...
      //$('textarea[name="'+elements[i].id+'"]').val(' ');
      //console.log($('textarea[name="'+elements[i].id+'"]').val());

      // better, to remove element from submit
      $('textarea[name="'+elements[i].id+'"]').attr('disabled', 'disabled');

    }
   }

  //return false; // if false, doesn't submit, good for testing
});

</script>
Categories: jQuery Tags: , ,

ajax – cross domain requests (jQuery)

July 22nd, 2009 dwright No comments

if you are using jQuery to make a ajax http resource request for content
located outside your domain, you will receive an error such as: (see Firebug error console)

uncaught exception: Access to restricted URI denied (NS_ERROR_DOM_BAD_URI)

it is a security violation to make a cross domain request.

there is a cool jQuery plugin that will enable you to get around this.
flXHR Proxy http://plugins.jquery.com/project/flXHR

caveat: you have to be able to put a file (crossdomain.xml) on the server you want to get content from
"flXHR uses flash (an invisible swf instance), it leverages Adobe's crossdomain.xml server opt-in policy model to allow the cross-domain communication."

take the follow jqGrid example:

jqGrid:
jQuery("#search_results").jqGrid(
{
url: "http://not_my_host.com/resource.php?query=&m=1&c=1&ps=1&pe=20&rid=3",
datatype: "xml",
...

by default will produce:
uncaught exception: Access to restricted URI denied (NS_ERROR_DOM_BAD_URI)

(after adding the crossdomain.xml to the remote host, using the plugin the request should work as desired)

more info about crossdomain.xml http://kb2.adobe.com/cps/142/tn_14213.html

crossdomain.xml, are placed at the root level of a server
here is an example file:

NOTE: I ended up using a different approach to this issue and did not confirm that the above actually works, if this works for you please let me know.
(This should also work if you are not using jQuery, you would just not use the plugin, you would use Adobe's solution)

Categories: ajax, jQuery Tags: , , ,