How to use offset (value) Method and offset () using function method in JQuery

In this article, I will explain use of offset (value) Method and how to use offset () method using function in JQuery.
  • 1854

Introduction

offset() method gets the current offset (position) for the selected elements,  in pixels.

JQuery CSS offset(val) method

offset(val) method sets the CSS coordinates of element.

  • value set the top and left coordinates in pixels.
  • Possible values:
    • Value pair, like {top:100,left:0}
    • An object with top and left properties

Syntax

$(selector).offset(value)

Example

The following example shows how to offset(val) method in jquery.

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("button").click(function () {

            $("p").offset({ top: 150, left: 10 });

        });

    });

</script>

</head>

<body>

<h3>offset(val) Example</h3>

<p style="background-color:Red">First paragraph.</p>

<button>Click for set the offset coordinates of the p element</button>

</body>

</html>

 

Output

 

 offset value.jpg

JQuery CSS offset() using function method

offset(fun) use a function to set the offset of elements.

Syntax

$(selector).offset(function(index,oldoffset))

Example

The following example shows how to offset() using function method in jquery.

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("button").click(function () {

            $("p").offset(function (n, c) {

                newPos = new Object();

                newPos.left = c.left + 80;

                newPos.top = c.top + 150;

                return newPos;

            });

        });

    });

</script>

</head>

<h3>offset() with function Example</h3>

<p style="background-color:Red">First paragraph.</p>

<button>Click for change paragraph coordinates</button>

</body>

</html>

 

Output

 

 offset funation.jpg

Further Readings

You may also want to read these related articles here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2013 dotNetheaven. All rights reserved.