I have this function that (on page load) changes my margin using the “css” jQuery method…
function page_change() {
var h = window.location.hash;
switch (h) {
case 'home':
$('.page-slide-box').css({marginLeft: 0});
break;
case 'history':
$('.page-slide-box').css({marginLeft: '-820px'});
break;
// more cases here.....
}
}
…but after the page is loaded, I’d like to animate the change instead. I was thinking I could alter the existing function using replace() (rather than writing another redundant function), like so:
window.onhashchange = function() {
var get = page_change.toString();
var change = get.replace(/css/g, 'animate');
page_change();
}
This successfully changes all instances of “css” to “animate” in my page_change() function. How do I get this function to change dynamically once I’ve replaced the strings? Or is this just a bad idea?
In your example, I’d say this is a terrible idea. Why not simply define 1 function that can do both, and use it accordingly:
call this function directly, and it’ll set the css, use it like so:
and it’ll
animateinstead of use thecssmethod. EasyIf you want to test this easily, you could try this:
That’s, basically, how this works.
The added benefit of defining a function like this (anonymous function, assigned to a variable or referenced by a var) is that you can easily assign a new function to that same variable:
This might work for you, too… of course. You can even store the old function:
Play around with this for a while, to find the approach that fits your needs best (it could well be a combination of the things I talked about in this answer)