Blouet
Blouet

Reputation: 11

how to add a css class in javascript to be used onload

I am trying to load a popup lightbox window when the page is initially opened. I can get it to work on a click but I cannot get the code right to add a class in the script. I am using 'Lightbox' from within HTML Kickstart.

The link that works looks like this: <a class="lightbox" href="#bbc">BBC</a> This works perfectly. Basically how do I get that to work automatically on page load.

My attempt at the script:

<script type="text/javascript">
    function load() {
        var target = location.href = "#bbc";
        target.className = "lightbox";
    }
</script> 

Upvotes: 0

Views: 6358

Answers (4)

FLX
FLX

Reputation: 2679

$(window).load(function () {
    var target = location.href = "#bbc";
    target.className = "lightbox";
});

Upvotes: 0

Pebbl
Pebbl

Reputation: 36015

The way I read this question — ignoring the title — is that the user is trying to trigger the lightbox on load. Whilst this may be a wrong assumption, the way to trigger a link using javascript is to use the .click() method:

window.onload = function(){
  var i, list = document.getElementsByTagName('a');
  for ( i=0; i<list.length; i++ ) {
    /// this will only work for links with only a class name of lightbox.
    /// you could look into using getElementsByClassName or something similar.
    /// I use getElementsByTagName because I know how supported it is.
    if ( list[i].className == 'lightbox' ) {
      list[i].click();
    }
  }
};

The above code would support multiple lightbox links in a page, which might not be desired, so it may be best just to add an id to the link you wish to target and then use:

window.onload = function(){
  document.getElementById('clickonload').click();
};

<a id="clickonload" class="lightbox" href="#bbc">BBC</a>

You may find however, that in reading the documentation for whatever lightbox plugin you are using, that there is a command you can use from JavaScript, rather than clicking a target link.

Upvotes: 0

MMM
MMM

Reputation: 7310

So I assume you want to add a class to that anchor tag:

$(function () {
    $("a[href=#bbc]").addClass("lightbox");
});

Using $(function() {…}) is the same as using the ready() function (in JQuery). I would recommend running the code after the DOM is ready rather the "on load".

Upvotes: 1

Pavan Kumar K
Pavan Kumar K

Reputation: 1376

you need to call the load() function on the onLoad event of <body> tag.

<body onLoad="load()">

Upvotes: 0

Related Questions