Carbonized Blog » Javascript http://carbonize.co.uk/wp Just a bunch of stuff Sat, 09 Aug 2014 07:58:45 +0000 en-US hourly 1 http://wordpress.org/?v=308 Animated Div Collapsing http://carbonize.co.uk/wp/2013/03/10/animated-div-collapsing/ http://carbonize.co.uk/wp/2013/03/10/animated-div-collapsing/#comments Sun, 10 Mar 2013 20:20:59 +0000 http://carbonize.co.uk/wp/?p=610 A few years ago I was looking for a simple JavaScript to animate the hiding/showing of a div. I came across one that was perfect from harrymaugans.com but the site is currently undergoing a revamp so the original post is no longer there. Anyway the script was perfect but it had one issue, it required that the div’s height be already set and I was working with dynamically populated divs that I wouldn’t know the size of. My original solution was to loop through the divs I was going to hide and set their height to what their height currently was (if that makes sense) before hiding them with display: none;. Anyway I got sidetracked and I felt this solution was inadequate anyway so left it in my test folder. Jump to the present day. I started looking at it again and realised I can grab the original height of the div once it’s display had been changed back to block by the script and it’s height set to 1px ready for the sliding into view. The solution was simply to use scrollHeight which gets the height of a div including any hidden content such as when overflow is set to hidden.

I also added a new function, toggleSlide, which means instead of needing a link to call the slideDown and then one to call the slideUp you can just call toggleSlide and it will either slide it up or down depending on it’s current state.

And so I am offering my version of the script here since I think some people might be in the same boat as me and find my solution useful and also because the original source is no longer available.

/* 
   Originally from http://www.harrymaugans.com/2007/03/06/how-to-create-an-animated-sliding-collapsible-div-with-javascript-and-css/
 
   Update by Carbonize - http://carbonize.co.uk 
   Date: Sun, 10 March 2013 20:15:24 GMT
 
   To use simply use slidedown(objects ID) to slide it down/open or slideup(object ID) to make it slide up/closed
 
   Or simpler yet I have added toggleSlide(object ID) so you can just call one function and it will automatically slide the object 
   up or down depending on it's current situation
 
  Please remember to set the elements overflow to hidden as in overflow: hidden; otherwise it's contents will be visible.
 
  And you might want to add return: false; when you call it to stop the link you are using from doing anything.
*/
var timerlen = 5;
var slideAniLen = 250;
 
var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();
 
function slidedown(objname){
  if(moving[objname])
          return;
 
  if(document.getElementById(objname).style.display != "none")
          return; // cannot slide down something that is already visible
 
  moving[objname] = true;
  dir[objname] = "down";
  startslide(objname);
}
 
function slideup(objname){
  if(moving[objname])
          return;
 
  if(document.getElementById(objname).style.display == "none")
          return; // cannot slide up something that is already hidden
 
  moving[objname] = true;
  dir[objname] = "up";
  startslide(objname);
}
 
function startslide(objname){
  obj[objname] = document.getElementById(objname);
 
  startTime[objname] = (new Date()).getTime();
 
  if(dir[objname] == "down"){
          obj[objname].style.height = "1px";
  }
 
  obj[objname].style.display = "block";
  endHeight[objname] = parseInt(obj[objname].scrollHeight);
 
  timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
}
 
function slidetick(objname){
  var elapsed = (new Date()).getTime() - startTime[objname];
 
  if (elapsed > slideAniLen)
          endSlide(objname)
  else {
          var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
          if(dir[objname] == "up")
                  d = endHeight[objname] - d;
 
          obj[objname].style.height = d + "px";
  }
 
  return;
}
 
function endSlide(objname){
  clearInterval(timerID[objname]);
 
  if(dir[objname] == "up")
          obj[objname].style.display = "none";
 
  obj[objname].style.height = endHeight[objname] + "px";
 
  delete(moving[objname]);
  delete(timerID[objname]);
  delete(startTime[objname]);
  delete(endHeight[objname]);
  delete(obj[objname]);
  delete(dir[objname]);
 
  return;
}
 
function toggleSlide(objname) {
  // Pointless going any further if we are already sliding the object
  if(moving[objname])
          return;
  if (document.getElementById(objname).style.display == 'none') {
    // div is hidden, so let's slide down
    slidedown(objname);
  } else {
    // div is not hidden, so slide up
    slideup(objname);
  }
}

Here’s some example HTML

<a onclick="toggleSlide('myDiv'); return false;" href="somewhere.php">Toggle Div</a>
]]>
http://carbonize.co.uk/wp/2013/03/10/animated-div-collapsing/feed/ 0
Random Character Generation in PHP and JavaScript http://carbonize.co.uk/wp/2012/02/08/random-character-generation-in-php/ http://carbonize.co.uk/wp/2012/02/08/random-character-generation-in-php/#comments Wed, 08 Feb 2012 16:29:07 +0000 http://carbonize.co.uk/wp/?p=486 I wrote this function in response to someone else’s attempt on a forum I was asked to join. It basically generates a string of random letters and numbers with the letters being in both upper and lower case. It is easy to edit it to only use upper or lower case letters or even add symbols as well. I initially wrote it in PHP and then rewrote it in JavaScript as well.

function randomString($strLen = 32)
{
  // Create our character arrays
  $chrs = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
 
  // Just to make the output even more random
  shuffle($chrs);
 
  // Create a holder for our string
  $randStr = '';
 
  // Now loop through the desired number of characters for our string
  for($i=0; $i<$strLen; $i++)
  {
    $randStr .= $chrs[mt_rand(0, (count($chrs) - 1))];
  }
  return $randStr;
}

Using it is simply a case of calling it and specifying how long to make the string otherwise it uses the default length of 32 characters.

echo randomString(12);

To also make it use symbols you just change the array_merge to


// If we want letters, numbers and symbols
$chrs = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9), array('!','£','$','%','^','&','*','(',')','-','=','+','@','#','~','?'));

Now for the JavaScript version. JavaScript has neither a range() function nor an easy way to shuffle an array so the code here is a little longer.

function randomString(len) {
  // Just an array of the characters we want in our random string
  var chrs = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
              'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
              '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
 
  // Check that a length has been supplied and if not default to 32
  len = (isNaN(len)) ? 32 : len;
 
  // The following section shuffles the array just to further randomise the output
  var tmp, current, top = chrs.length; 
  if(top)
  {
    while(--top) 
    { 
      current = Math.floor(Math.random() * (top + 1)); 
      tmp = chrs[current]; 
      chrs[current] = chrs[top]; 
      chrs[top] = tmp; 
    }
  }
 
  // Just a holder for our random string
  var randomStr = '';
 
  // Loop through the required number of characters grabbing one at random from the array each time
  for(i=0;i<len;i++) 
  {
    randomStr = randomStr + chrs[Math.floor(Math.random()*chrs.length)];
  }
 
  // Return our random string
  return randomStr;
}
]]>
http://carbonize.co.uk/wp/2012/02/08/random-character-generation-in-php/feed/ 0
Top Ten Javascript Functions http://carbonize.co.uk/wp/2009/04/28/top-ten-javascript-functions/ http://carbonize.co.uk/wp/2009/04/28/top-ten-javascript-functions/#comments Tue, 28 Apr 2009 04:13:07 +0000 http://carbonize.co.uk/wp/?p=260 Whilst surfing the ether we call the internet I came across a list of top ten javascript functions by Dustin Diaz. As the saying goes it does exactly what it says on the tin. It is a collection of ten (and a bonus one) basic javascript functions that most Javascript writers will need/use quite a lot. Such functions as adding onload events to the window even if you’re not sure that it’s already been set by another script. getElementByClass which to me is something that should of been in Javascript from the start :mad: . If you write Javascript then you will find atleast one of the functions useful.

And I know it was written in 2005 but the functions are just as valid today.

]]>
http://carbonize.co.uk/wp/2009/04/28/top-ten-javascript-functions/feed/ 2
Browser Wars http://carbonize.co.uk/wp/2009/03/18/browser-wars/ http://carbonize.co.uk/wp/2009/03/18/browser-wars/#comments Wed, 18 Mar 2009 19:02:29 +0000 http://carbonize.co.uk/wp/?p=186 OK thanks to Google’s Chrome and Apple now making Safari a serious browser for Windows the browser war is getting ridiculous. They all seem obsessed with how fast their Javascript engines run with Google now saying the V8 engine in Chrome 2 is 25% faster than in Chrome 1. Who cares? The speed of the Javascript engines is now so fast few people if any would be able to notice a difference in everyday use. The only people who are are Geeks who think the extra milliseconds make all the difference.

I’m not interested in how fast their Javascript engines run I just want a browser that is configurable and doesn’t eat up resources. I’m sticking with Firefox at present as it lets me configure cookies exactly how I want and has some sweet extensions. I am impressed with the WebKit engine as used in Chrome and Safari. To me Opera fell to the wayside with version 7. So at some point I may switch from Firefox to Safari or Chrome but can’t see it anytime soon. Safari 4 beta looks good but is all eye candy and eats memory. Chrome is to basic with very limited options and no black/white list for cookies. Safari also has neither a whitelist nor blacklist.

]]>
http://carbonize.co.uk/wp/2009/03/18/browser-wars/feed/ 1
Javascript To Change Image On Link Click http://carbonize.co.uk/wp/2008/08/23/javascript-to-change-image-on-link-click/ http://carbonize.co.uk/wp/2008/08/23/javascript-to-change-image-on-link-click/#comments Sat, 23 Aug 2008 22:32:26 +0000 http://www.carbonize.co.uk/Blog/archives/49-guid.html I recently decided to add the ability for guests to request a new captcha image (or refresh the captcha image) in my guestbook script for when it was to hard for visitors to read. As usual trying to find some instructions to do this proved useless so I had to figure it out myself. I thought I would explain how it’s done here for anyone else wanting to do this and believe me it’s very very simple.

Ok first thing we need to do is give a name to the image we are going to by replacing/changing so we add a name. For the guestbook script I added added name=”lazCaptcha” to the image tag.

eg:

<img src="http://domain.com/path/image.jpg" name="NAMEFORIMAGE" alt="" />

Next we need to create the link that the viewer clicks on to replace/change the image and for that I used this bit of code:

<a href="#" onclick="reloadImage('NAMEFORIMAGE'); return false;">request another image</a>

Notice how I put the name of the image into the Javascript? Thats so we can use this code multiple times on a single page.

Next we need the Javascript and it is very simple. We just create a random number to add to the image url to prevent it showing the cached image and then tell the browser to change the image. I’ll show two examples. The first is just when we want to display a random image and the second is how I display a new captcha image with the same code.

Random Image:

function reloadImage(imageName)
{
var myImages=new Array();
myImages[0]="sun.jpg";
myImages[1]="moon.jpg";
myImages[2]="stars.jpg";
// Create a random number between 1 and one greater than the number of items in the array
var randomImage = Math.floor(Math.random() * (myImages.length + 1));
randomImage--;
// Change the image
document.images[imageName].src = 'http://yoursite.com/path/to/' + myImages[randomImage];
}

Captcha Image:

function reloadImage(imageName)
{
// Create a random number between 1 and 1000
var randomnumber=Math.floor(Math.random()*1001);
// Change the image
document.images[imageName].src = 'http://yoursite.com/path/image.php?hash=OURHASH&rand=' + randomnumber;
}

OURHASH? What’s that? :-? Well if you are planning to refresh a captcha image then I’m guessing you have generated the form the image is displayed in and so you can just use the variable you used for the hash in the image tag to put the hash in the javascript image tag. Or you could just change that line to

document.images[imageName].src = document.images[imageName].src + '&rand=' + randomnumber; // Change the image

And thats it. See how simple it is to do? ;-)

]]>
http://carbonize.co.uk/wp/2008/08/23/javascript-to-change-image-on-link-click/feed/ 0