0

Ok so I'm trying to remove an object called Comment from the main Html file. Here's the code:

function Comment(message){
var self = this;
var child = null;
var message = message;

var comment = document.createElement("div");
comment.id = "comment";
comment.textContent = message;

var replyField = document.createElement("ul");

var reply = document.createElement("input");
reply.type = "submit";
reply.value = "reply";
comment.appendChild(reply);

var deleteBtn = document.createElement("input");
deleteBtn.type = "submit";
deleteBtn.value = "delete";
deleteBtn.addEventListener("click", function(comment){deleteComment(comment)},false);
comment.appendChild(deleteBtn);
comment.appendChild(replyField);

return comment;
}
function deleteComment(comment){
    var parent = document.getElementById("wall");
    parent.removeChild(comment);
}

Once I have created the "Comment object" and prepended it to a <ul id="wall">, the delete button does not work for some reason. Can Anyone help me?

here is the html code:

<head>
<script type="text/javascript" src="Jquery/jquery-1.4.4.js"> </script>
<script type="text/javascript" src="src/Comment.js"> </script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("form#newMessage").submit(function(){
            var message = $("input#newMessageTxt").val();
            var newComment = new Comment(message);
            var commentHtml = newComment.outerHTML;

            $("ul#wall").prepend('<li style="display: none;">'+commentHtml+"</li>");
            $("ul#wall li:first").fadeIn();
        });
    });
</script>
</head>

<body>
    <div class="message">
        <form id="newMessage"&gt;>
            <input type="text" id="newMessageTxt" height="200px" value="Write a message" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;" />
            <input type="submit" value="Submit"></button>
        </form>
    </div>
    <ul id="wall">
    </ul>
</body>
2
  • why don't you use JQuery? It will seriously make your life easier Commented Dec 19, 2010 at 2:48
  • @Jacob Relkin I made it work but now I cannot use the fadeIn() that I wanted to use inside the html file Commented Dec 19, 2010 at 4:31

3 Answers 3

2

I think that this line:

deleteBtn.addEventListener("click", function(comment){deleteComment(comment)},false);

Should look like this:

deleteBtn.onclick = function(e) {
   deleteComment(comment);
   return false;
};

EDIT:

In response to your updated question, this line:

var newComment = new Comment(message);

Should be this:

var newComment = Comment(message);
Sign up to request clarification or add additional context in comments.

2 Comments

deleteComment(this); ? this is the deleteBtn, you mean deleteComment(comment);
Regarding your update: That does not matter. If you call a function constructor (new Func()) and this function returns an object explicitly, then this is totally fine. If the function does not return an object, the object this is implicitly returned.
0

Since there's clearly a problem somewhere else... and since you're not fully using the potential of JQuery, I've taken the liberty of rewriting the code you've provided. Here it is :

<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"> </script>
    <script type="text/javascript">
        var _comment_counter = 0;
        function Comment(msg){

            var comment = $('<div></div>')
                .attr('id', "comment" + (_comment_counter++))
                .text(msg);

            $('<input type="submit"></input>').val('reply')
                .appendTo(comment);
            $('<input type="submit"></input>').val('delete')
                .click(function() { deleteComment(comment); })
                .appendTo(comment);

            $('<ul></ul>')
                .appendTo(comment);

            return comment;
        }
        function addComment(comment) {
            $("ul#wall").prepend(
                $('<li></li>').hide().append(comment).fadeIn()
            );
        }
        function deleteComment(comment){
            comment.parent().fadeOut('normal', function() { $(this).remove(); });
        }
    </script>
    <script type="text/javascript">
        $(document).ready(function(){
            var _defaultValue = "Write a message";
            $("#newMessageTxt")
                .height("200px")    // ??? use a textarea ?
                .val(_defaultValue)
                .focus(function() {
                    if ($(this).val() == _defaultValue) {
                        $(this).val('');
                    }
                })
                .blur(function() {
                    if(/^\s*$/.test($(this).val())) {
                        $(this).val(_defaultValue);
                    }
                })
            ;

            $("form#newMessage").submit(function(){
                var msg = $("input#newMessageTxt").val();
                if (msg != _defaultValue) {
                    var newComment = new Comment(msg);

                    addComment(newComment);

                    $("input#newMessageTxt").val(_defaultValue);
                }

                return false;
                });
        });
    </script>
</head>

<body>
    <div class="message">
        <form id="newMessage">
            <input type="text" id="newMessageTxt" />
            <input type="submit" value="Submit" />
        </form>
    </div>
    <ul id="wall">
    </ul>
</body>

** TIPS **

  • adopt a coding style, and use it everywhere
  • if you're using a library, use it or else you're not respecting the point above
  • separate code and layout; HTML is a layout, Javascript is code. You shouldn't put socks in your t-shirt drawer...
  • if you have a delete function, you should have an add function. This goes for all CRUD operations

Now, this code works, you should perhaps start from there.

Comments

0

The object passed to an event handler is an event object. You cannot define your own parameters in an event handler. So if you define comment as parameter, it will refer to the event object. Just do remove it or rename it to something else (e.g. event ;)):

deleteBtn.addEventListener("click", function(){deleteComment(comment)},false);

comment in the event handler will refer to comment defined in the outer function. The function you pass as event handler is a closure.

Side notes:

  • Instead of creating a new button, you can save a line of code and clone the previous created button:

    var deleteBtn = reply.cloneNode();
    deleteBtn.value = "delete";
    
  • Instead getting the parent by ID, make us of the parentNode property:

    function deleteComment(comment){
        comment.parentNode.removeChild(comment);
    }
    
  • If you append a new comment directly to <ul id="wall"> then you create non-valid HTML. A list (<ul>) can only contain <li> elements.

  • To be complete: IE uses a different event model and the method to attach events is called attachEvent. See quirksmode.org for more details.

Update:

Here is a DEMO which works in all W3C conform browsers ;)

Update 2:

As others say, if you use jQuery anyway, use it throughout your code. Here is another example how you can improve your code:

function getComment(message) {
    var comment = $('<div />', {
        "class": "comment",
        text: message
    }).append($('<input />', {
        type: "submit",
        val: "reply"
    })).append($('<input/>', {
        type: "submit",
        value: "delete",
        click: function() {
            $(this).parent().remove();
        }
    })).append('<ul/>');
    return comment;
}

$("form#newMessage").submit(function() {
    var message = $("#newMessageTxt").val();
    $('<li />', {
        style: "display:none"
    }).append(getComment(message)).appendTo('#wall').fadeIn();
    return false;
});

DEMO

7 Comments

also note that addEventListener will not work prior to IE9 (developer.mozilla.org/en/DOM/element.addEventListener)
@Yanick Rochon: Yep, I hope the OP knows that ;)
I tried this and tested it in Dreamweaver using the live view mode (since it's only front end) and it didn't work.
@twidizle: See my update. I created a demo and it works. Run it in Firefox or Chrome. If it does not work, the error is somewhere else in your code.
I just posted an update to my question... look at the html code. I don't know why it's not working
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.