Deniz
Deniz

Reputation: 53

event.preventDefault() on hyperlink not working

I'm aware that this issue was addressed many times, that's why I read most of the topics on this problem that were already opened on Stack Overflow but none of the suggestions have helped me.

I have a list of div elements, each containing a hyperlink and a span element with additional information. The span elements are initially hidden and they need to be toggled whenever the sibling anchor element is clicked.

<div class="politician">
    <a href="">
        Антонијо Милошоски
    </a>
    <span class="additional" style="display: none">
        2013ВМРО-ДПМНЕ1997-1
    </span>
</div>
<div class="politician">
    <a href="">
        Силвана Бонева
    </a>
    <span class="additional" style="display: none">
        2013ВМРО-ДПМНЕ1991-1
    </span>
</div>

Here's the jQuery code I have written to handle the toggling of the hidden elements:

    $('.politician a').click(function (e) {
        e.preventDefault();
        var $this = $(this).parent().find('span');
        $(".politician span").not($this).hide();
        $this.toggle();
    });

My problem was already stated in the title. I'm expecting the hidden elements to be shown, but instead the page gets refreshed. I guess there has to be something wrong with the way I'm using the preventDefault() method.

EDIT

Here is the piece of code that generates the div.politician elements.

        function populateList(politicians) {
        var politlist = $("#list").html("");
        for (var i in politicians) {
            var person = politicians[i];
            var politinfo = "<div class=\"politician\"><a href=\"\">" + person.name + " " + person.surname + "</a><span class=\"additional\" style=\"display: none\">" + person.lastserved;

            for (var j in person.member)
            {
                var membership = person.member[j]
                politinfo += membership.party + membership.enrol + membership.leave;
            }

            politinfo += "</span></div>";
            $(politinfo).appendTo(politlist);
        }
    }

Upvotes: 1

Views: 2904

Answers (2)

billyonecan
billyonecan

Reputation: 20270

Since you're adding elements dynamically, you need to use event delegation:

$('#list').on('click', '.politician a', function(e) {
   // your code 
});

Upvotes: 3

Michał Lach
Michał Lach

Reputation: 1278

This is happending because your html is not loaded when you add click event listener to it. Wrap your code in document.ready function, like this:

$(function(){
     $('.politician a').click(function (e) {

        var $this = $(this).parent().find('span');
        $(".politician span").not($this).hide();
        $(this).toggle();
        e.preventDefault();
    });

});

http://plnkr.co/edit/gist:1986619?p=preview

Upvotes: 1

Related Questions