51

Let's say I want that every time the user click any link an alert pops up that says "hohoho". Do I need to add onclick="alert('hohoho')" to every link or can I set this with CSS so that it works with every link?

9 Answers 9

96

You can't do it with just CSS, but you can do it with Javascript, and (optionally) jQuery.

If you want to do it without jQuery:

<script>
    window.onload = function() {
        var anchors = document.getElementsByTagName('a');
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            anchor.onclick = function() {
                alert('ho ho ho');
            }
        }
    }
</script>

And to do it without jQuery, and only on a specific class (ex: hohoho):

<script>
    window.onload = function() {
        var anchors = document.getElementsByTagName('a');
        for(var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];
            if(/\bhohoho\b/).match(anchor.className)) {
                anchor.onclick = function() {
                    alert('ho ho ho');
                }
            }
        }
    }
</script>

If you are okay with using jQuery, then you can do this for all anchors:

<script>
    $(document).ready(function() {
        $('a').click(function() {
            alert('ho ho ho');
        });
    });
</script>

And this jQuery snippet to only apply it to anchors with a specific class:

<script>
    $(document).ready(function() {
        $('a.hohoho').click(function() {
            alert('ho ho ho');
        });
    });
</script>
6
  • 30
    Or you could use document.getElementsByClassName("class")
    – JCOC611
    Commented Jan 3, 2011 at 22:11
  • Incredible, so it can indeed actually be done without a library! I found an excellent article about JS events as well.. howtocreate.co.uk/tutorials/javascript/domevents Commented Jan 3, 2011 at 22:12
  • @JCOC611: I didn't use getElementsByClassName because it doesn't work on every major browser.
    – Alex Vidal
    Commented Jan 3, 2011 at 22:14
  • @luminarious: Yay, everything can be done without a library! @Alex: :O I didn't know, I don't use it anyways lol...you mean IE, right?
    – JCOC611
    Commented Jan 3, 2011 at 22:16
  • 1
    2020 here, you can use getElementsByClassName on all browsers safely: caniuse.com/getelementsbyclassname
    – Fanky
    Commented Dec 5, 2020 at 10:49
45

You can do this by thinking of it a little bit differently. Detect when the body is clicked (document.body.onclick - i.e. anything on the page) and then check if the element clicked (event.srcElement / e.target) has a class and that that class name is the one you want:

document.body.onclick = function(e) {   //when the document body is clicked
    if (window.event) {
        e = event.srcElement;           //assign the element clicked to e (IE 6-8)
    }
    else {
        e = e.target;                   //assign the element clicked to e
    }

    if (e.className && e.className.indexOf('someclass') != -1) {
        //if the element has a class name, and that is 'someclass' then...
        alert('hohoho');
    }
}

Or a more concise version of the above:

document.body.onclick= function(e){
   e=window.event? event.srcElement: e.target;
   if(e.className && e.className.indexOf('someclass')!=-1)alert('hohoho');
}
1
  • 1
    I had issues with document.body.onclick, but it seems to work well with document.onclick. Commented Feb 13, 2018 at 10:04
11

You could do it with jQuery.

$('.myClass').click(function() {
  alert('hohoho');
});
4
  • Is it possible with just css and javascript though?
    – Juan
    Commented Jan 3, 2011 at 22:05
  • 1
    jQuery is a javascript library, so it already is just HTML/CSS/JS
    – zzzzBov
    Commented Jan 3, 2011 at 22:07
  • 1
    Yes, but you'd have to write your own JavaScript code to iterate the elements in the DOM and query their attributes to see if a css class is applied to them and then take action. For example: howtocreate.co.uk/tutorials/javascript/domcss but in my opinion the amount of code you'll have to write to be safe about it is not worth it compared to using a community-backed, free project.
    – Erik Noren
    Commented Jan 3, 2011 at 22:09
  • @jsoldi I'm not a mind-reader, and your comment didn't give me any confidence in your knowledge of HTML/CSS/JS.
    – zzzzBov
    Commented Jan 3, 2011 at 22:17
4

It can't be done via CSS as CSS only changes the presentation (e.g. only Javascript can make the alert popup). I'd strongly recommend you check out a Javascript library called jQuery as it makes doing something like this trivial:

$(document).ready(function(){
  $("a").click(function(){
    alert("hohoho");
  });
});
4

Following JCOC611 suggestion:

window.onload = function() {    
    let elements = document.getElementsByClassName("someClassName");

    for(let i = 0; i < elements.length; i++) {
        elements[i].onclick = function () {
            alert("Clicked in an element of the class.");
        }
    }
};
3

Here is my solution through CSS, It does not use any JavaScript at all

HTML:

<a href="#openModal">Open Modal</a>

<div id="openModal" class="modalDialog">
        <div>   <a href="#close" title="Close" class="close">X</a>

                <h2>Modal Box</h2>

            <p>This is a sample modal box that can be created using the powers of CSS3.</p>
            <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>
        </div>
    </div>

CSS:

.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.8);
    z-index: 99999;
    opacity:0;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    pointer-events: none;
}
.modalDialog:target {
    opacity:1;
    pointer-events: auto;
}
.modalDialog > div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
    background: -moz-linear-gradient(#fff, #999);
    background: -webkit-linear-gradient(#fff, #999);
    background: -o-linear-gradient(#fff, #999);
}
.close {
    background: #606061;
    color: #FFFFFF;
    line-height: 25px;
    position: absolute;
    right: -12px;
    text-align: center;
    top: -10px;
    width: 24px;
    text-decoration: none;
    font-weight: bold;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    -moz-box-shadow: 1px 1px 3px #000;
    -webkit-box-shadow: 1px 1px 3px #000;
    box-shadow: 1px 1px 3px #000;
}
.close:hover {
    background: #00d9ff;
}

CSS alert No JavaScript Just pure HTML and CSS

I believe that it will do the trick for you as it has for me

2

Many 3rd party JavaScript libraries allow you to select all elements that have a CSS class of a particular name applied to them. Then you can iterate those elements and dynamically attach the handler.

There is no CSS-specific manner to do this.

In JQuery, you can do:

$(".myCssClass").click(function() { alert("hohoho"); });
2

Asking about "a class" in the question title, the answer is getElementsByClassName:

  var hrefs = document.getElementsByClassName("YOUR-CLASS-NAME-HERE");
  for (var i = 0; i < hrefs.length; i++) {
   hrefs.item(i).addEventListener('click', function(e){
    e.preventDefault(); /*use if you want to prevent the original link following action*/
    alert('hohoho');
   });
  }
0

I liked the @kennebec solution, but it fails when there are embedded elements such as:

<span class='my_popup'>Click <i>this!</i></span> 

This is fixed using:

document.body.onclick= function(e) {
  e= window.event ? event.srcElement:e.target;
  if(e= isClass(e,'my_popup')) {
    alert('hohoho');
  }
  function isClass(e,n) {
    if(e.className && e.className.indexOf(n)!=-1)
      return(e);
    if(e.parentNode)
      return(isClass(e.parentNode,n));
    return(null);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.