Drawing a vertical line in jQuery

13 October, 2013 by Tom Elliott

There are many ways we can manipulate HTML and CSS in JavaScript to create various shapes and patterns. I was recently working on a jQuery project where I needed to connect two images with a simple line and found myself searching ‘Creating a vertical line in jQuery’, when I released I could just write a line drawing function in a few minutes.

The below jQuery function takes in 5 parameters, setting the properties of a div element for the width, height, colour and left and right position respectively. By setting the width of the div to just a few pixels, we get a thin line.

//Function to draw a vertical line
function draw_vertical_line(width, height, linecolor, xpos, ypos) {
	$('#line').css({'width':width, 'height':height, 'background-color':linecolor, 'left':xpos, 'top':ypos, 'position':'absolute'});
}

draw_vertical_line(1, 100, '#357d35', 50, 10);

The example above will draw a vertical line with a width to 1 pixel, height of 100 pixels and coloured green using a hex code value. The last 2 parameters will create the line 50 pixels across and 10 pixels down:

You will also need the below HTML, within the parent element of where you want the line to appear.

<div id="line"></div>

As the line is absolutely positioned, you may want to set the parent positioning to ‘relative’ so the left and right position of the line is relative to the parent.

You could of course use this function to create a horizontal line instead, or any sized div element for that matter.



2 Comments

  • Tobi says:

    The code is not working – you set up the function with “drawverticalline” and call the function with “draw_vertical_line”. It has to be the same.

    If it’s fixed, it’s very helpful! 🙂

  • Ameen says:

    I need something link animated line pattern creating from one end to another end on scroll.