Archive for JavaScript

JavaScript Global Replace Using Regular Expressions

I find the String.replace() functionality of JavaScript to be a bit more than annoying. This is because of one crucial reason.

When you do this:

'Hey there!'.replace('e', 'a');

coming from most backgrounds, you’d expect this:

'Hay thara!'

but you end up with this:

'Hay there!'

Wha?? Talk about running into debug issues and pulling your hair out.

The issue is that the default behavior is to just replace the first instance of a string. Personally, I’m not quite sure why this is the case, but the fact remains that it is. Now, another option is to use regular expressions. Let’s try:

'Hey there!'.replace(/e/, 'a');

Still, no dice. You get:

'Hay there!'

Egads!

However, if you do:

'Hey there!'.replace(/e/gi, 'a');

You’re then using the global regular expression replacement, so you get:

'Hay thara!'

Finally, just what we were looking for! So, note that anytime you do 'original string to search within'.replace(/string to look for/gi, 'string to replace with'), then you’ll end up with what you expected – a global replace-all function throughout the string.

No comments, be first...

January 19, 2012

Yes, I Position My Background Image with jQuery

So, notice that green hook on the left there? How much of it can you see? And what happens if you resize the window?

Now, if you’re a front-end guy, you know that a background image cannot extend outside of an element. But what if you want to position that background relative to the position of an element, but outside of that element? I had the same problem…

Now, I’m a huge fan of jQuery, so I decided to go that route. Here’s what I did:

$('body')
    .css('background-position',
        $('#container').offset().left - 320 + 'px ' +
        $('#container').offset().top + 'px');

What does that do? jQuery finds the body element: $('body') and it sets the background position using .css('background-position', value). But, we need to get the position of my #container element, so we do that using $('#container').offset().left (with a 320px nudge) and $('#container').offset().top.

Put that in jQuery’s $(document).ready(function() and huzzah!

Well, what happens if you resize? Uh-oh, one more thing to do. I promise it won’t be hard though. Let’s just bring jQuery to the rescue again using $(window).bind('resize', function(). And, to keep up with DRY coding principles, we’ll pull it out into an alignBG() function, giving us:

function alignBG(){
    $('body')
        .css('background-position',
            $('#container').offset().left - 320 + 'px ' +
            $('#container').offset().top + 'px');
}

$(document).ready(function(){
    alignBG();

    $(window).bind('resize', function() {
        alignBG();
    });
}

And there you have it! That’s how you can position a background image based on a different element’s location in jQuery making sure that it’s in the right place on a resize.

7 comments

October 25, 2009