Search code examples
javascriptjquerycssbookmarkletbookmarks

CSS not applying in bookmarklet


I'm creating a simple bookmarklet (never done this before) and while the script executes just fine (doesn't do much right now), the CSS style sheet that gets embed doesn't apply to the HTML.

The activation link is as follows (domain changed):

<a href="javascript:(function(){document.head.appendChild(document.createElement('script')).src='http://www.mydomain.co.uk/cloudlr/app/js/cloudlr.js?rand=' + Math.floor(Math.random()*99999);})();">Do this</a>

Then the script called is:

if (typeof jQuery == 'undefined') {

    appendjQuery();

} else {

    jsVersion = $().jquery;
    versionArray = jsVersion.split('.');

    if (versionArray[1] < 6) {

        appendjQuery();

    } else {

        runthis();

    }
}

function appendCSS() {

    var cloudlrCSS = document.createElement('link');
    cloudlrCSS.type = 'text/css';
    cloudlrCSS.href = 'http://www.mydomain.co.uk/cloudlr/app/css/screen.css';
    cloudlrCSS.media = 'all';
    document.head.appendChild(cloudlrCSS);

}

function appendjQuery() {

    var cloudlrJS = document.createElement('script');
    cloudlrJS.type = 'text/javascript';
    cloudlrJS.onload = runthis;
    cloudlrJS.onreadystatechange = function () {

        if (this.readyState == 'loaded' || this.readyState == 'complete') {
            runthis();
        }

    }
    cloudlrJS.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js';
    document.head.appendChild(cloudlrJS);
}

function runthis() {

    appendCSS();

    $(document).ready(function() {

        $("img").each(function() {
            var $this = $(this);
            var imageWidth = $(this).width();
                $(this).before(imageWidth);
        });

        var cloudlrOverlay = '<div id="cloudlr-content">This is some content.</div><div id="cloudlr-overlay"></div>';

        $("body").append(cloudlrOverlay);

    });


}

Hopefully that's all pretty straightforward.

The scripts execute just fine (jQuery) but no CSS is applied. If I view the "generated source" I can see that the CSS was inserted fine and the link to the file works. So I'm not sure what's going on.

I'm new to this and would welcome any additional recommendations on best practices as well as a solution to the problem.

Many thanks, Michael.


Solution

  • $("img").each(function(i,n) {
        var $this = $(n);//don't know why this is here but hey
        var imageWidth = $(n).width();
            $(n).before(imageWidth);
    });
    

    this is a common mistake ... I think this could help you