views:

60

answers:

2

This is probably a noob question, but how I've implemented the appendTo() function below doesn't work as expected. Basically, it added the element and instantly removed it again. It's blink and you miss it stuff.

Can anyone understand why this might be happening?

Here's where the function gets called:

<?php foreach ($words as $word) {
echo    "<li class='$word[0]'><a href='' onclick='add_to();'>$word</a></li>";
} 

And here's the function itself (pretty much taken from the jQuery tutorial site:

function add_to () {
        $('<h1>Test</h1>').appendTo('.ad_text');
    }

My first thought is that a script that calls document.ready() is called, which wipes out the add_to() function? That script is above add_to(), and is this:

$(document).ready(function(){

        //when a link in the filters div is clicked...
        $('#filters a').click(function(e){

            //prevent the default behaviour of the link
            e.preventDefault();

            //get the id of the clicked link(which is equal to classes of our content
            var filter = $(this).attr('id');

            //show all the list items(this is needed to get the hidden ones shown)
            $('#content ul li').show();

            /*using the :not attribute and the filter class in it we are selecting
            only the list items that don't have that class and hide them '*/
            $('#content ul li:not(.' + filter + ')').hide();

        });

    });

Possibly a conflicting bit of code there? Sorry - new to Javascript, and trying to cobble something together quickly.

TIA, Andy

+5  A: 

Your link is reloading the page. Try this (added # to the href attribute)

foreach ($words as $word) {
    echo    "<li class='$word[0]'><a href='#' onclick='add_to();'>$word</a></li>";
}
Nalum
+1 - Good catch, completely missed this
Nick Craver
so get rid of the # in the href?
The Pied Pipes
oh sorry, just saw that you added a #! thanks!
The Pied Pipes
that's done it. thanks a lot @Nalum
The Pied Pipes
no problem should have put in your code then mine, will make it clearer now.
Nalum
@Nalum @NickCraver the above solution worked fine when appending content into a div. However, when I tried to add the same content to a textarea tag within the HTML, nothing happens. Any idea why this would be?
The Pied Pipes
Add `return false;` to the end of function which handles onclick event. This will prevent from following the link (and adding ugly # to the url).
skalee
Nalum
A: 

I can't say for sure but you might be overriding the click function that you defined in the onclick attribute with the one in the document.ready function.

adriaanp
It's important to distinguish that he/she's not *overriding*, they're *adding* a click handler, if that link is inside `#filters` that is.
Nick Craver
yep, Nick's right. and Nalum's addition of the hash anchor worked. however, I did run into trouble when trying to appendTo() into a textarea tag. Any suggestions?
The Pied Pipes