How can I run a script on page load?

49 views Asked by At

this script is drawing a line from top to bottom, but its starts on mouseover "onhover" and I want it to draw it when page is opened.

This is the whole code to be clear. The only thing it makes to be functional is hover from this line $( this ).hover(function().

var animationDuration = "0.4"
var backgroundColor = "white"

$.fn.line = function liner(animationDuration, borderWidth, side, backgroundColor) {
    var className = "line"
    var timePerSide = animationDuration

    $(this).append('<div class=' + className + '> <div></div> </div>');

    $(this).children("." + className).css({
        "-webkit-transition": "all " + timePerSide + "s linear " + timePerSide * 0 + "s",
        "transition": "all " + timePerSide + "s linear " + timePerSide * 0 + "s",
        "background-color": backgroundColor,
    });

    switch (true) {
        case side == "right":
            $(this).children(".line").css({
                "top": "0",
                "right": "-10",
                "height": "0%",
                "width": borderWidth,
            });
    }

    if (side == "right") {
        $(this).hover(function () {
            $(this).children(".line").css({
                "height": "150%",
            });
        });
    }
};

And this is my HTML

<body>
<div class="box1 float-left liner">
<h1>Lorem</h1>
</div>
</body>
<script type="text/javascript">
    $( document ).ready(function() {
        $('.liner').line(animationDuration, "5px", "right", backgroundColor);
    });
    </script>
</html>
1

There are 1 answers

2
isherwood On

It sounds like you want to ignore the hover function and simply run a portion of the plugin on load. You'll have to modify the plugin, which may not be idea. Instead of this:

if (side == "right") {
    $(this).hover(function () {
        $(this).children(".line").css({
            "height": "150%",
        });
    });
}

... simply do this:

if (side == "right") {
    $(this).children(".line").css({
        "height": "150%",
    });
}

If you need the code to run on both events, you might pull the inner portion out into a named function and call it for both:

function setLineHeight(els) {
    $(els).children(".line").css({
        "height": "150%",
    });     
}

... and then:

if (side == "right") {
    $(this).hover(function () {
        setLineHeight(this);
    });

    setLineHeight(this); // called when the plugin is initialized (on document.ready)
}