About that jQuery Mobile trick: Correction

1 min read 3 comments

Faithful readers. There was an error in my previous post about refreshing styles in a jQuery Mobile app!

Ahhh!!! I can hear you screaming. Calm down; I have a fix!

(Warning: I’m not 100% sure I understand this fix; but hey, it’s JavaScript! Nobody really understands1 it, right?)

A refresher: what I suggested was this:

function refreshStyles( $element ) {
  var $wrapper = $element.wrap( "<div>" ); // This is a mistake!
  $wrapper.page();                         // This doesn't work!
  $element.unwrap();
}

The above code doesn’t work because wrap returns the wrapped element (not the wrapper element).

Here’s that fix I mentioned (incidentally, this is how it was coded in our code base at work all along… go figure):

function refreshStyles( $element ) {
  $element.wrap( '<div id="refresh-styles-wrapper">' ); // Look Ma, no local!
  $("#refresh-styles-wrapper").page();                  // Egads! It works!
  $element.unwrap();
}

So yeah, somehow forcing jQuery to re-find the wrapper element makes everything honky dory. And if you don’t believe me, check it out:

Proof.


  1. I have this theory that JavaScript is the language with the greatest percentage of hackers, as opposed to actual developers. By which I mean, most of us just fiddle around with JS code until it works; but we don’t entirely get what we’re doing. At least that’s the case with me. (Don’t tell my employer.) ↩

Comments

This blog used to have comments, powered by Disqus. Comments are closed now, but the conversation that happened here is preserved below.

  1. Pete Hodgson

    I couldn't help fiddling with this, and came up with a slightly more succinct solution:

    [sourcecode language="javascript"]
    function refreshStyles( $element ) {
    $element.wrap( '<div>' ).parent().page();
    $element.unwrap();
    }
    [/sourcecode]

    And then I went crazy and made it a little TOO succinct (but still correct):

    [sourcecode language="javascript"]
    function refreshStyles( $element ) {
    $element.wrap( '<div>' ).parent().page().end().unwrap();
    }
    [/sourcecode]

    1. Pete Hodgson

      My divs got eaten. Both of those calls to wrap should have a string param specifying a div.

      Maybe wordpress will prefer this way of encoding it: $element.wrap( "<div>" )

      1. Dan Tao

        Pete: Nice edit! It's funny; I realized somewhat later after posting this that the reason my original version didn't work is that wrap returns the child element, not the parent, and thus going through the trouble of re-querying the DOM for the wrapper wasn't really necessary (i.e., using parent would do the trick, as you've done). Apparently I was too lazy to refactor, though. Also, I fixed your original comment using Wordpress's awesome syntax.