Append vs After method jQuery


#1
<!DOCTYPE html>
<head>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
  <body>

    <h1>Course Catelog</h1>
    <h3>Below is a list of course offerings to choose from</h3>

    <div id="course_name">
        <input type="textbox"></input>
    </div>
    <div id="div1" class="div_next">
        <button id="btn_1">Add Course</button>
    </div>
    <div id="statement">
        <h3></h3>
    </div>
    <div>
        <p>Below is a list of all the available courses <br>
        that can be enrolled in this semester:
        </p>
    </div>
    <ul id="courses">
      <li>Sociology</li>
      <li>Psychology</li>
      <li>Mathematics
        <ul id="math_subjects">
        <li>Algebra</li>
        <li>Geometry</li>
        <li>Calculus</li>
        </ul>
      </li>
      <li>Sciences
          <ul id="science_subjects">
          <li>Geology</li>
          <li>Physics</li>
          <li>Chemistry</li>
          </ul>
      </li>
      <li>World History</li>
    </ul>

        <script src="js/jquery-3.1.1.min.js"></script>
        <script src="js/custom_jquery_code.js"></script>

  </body>
</html>
----------------------------------------------------------------------------------------------------
.div_next {
    display: inline-block;
}

-----------------------------------------------------------------------------------------------------
$(function(){

       var $inputval;
	$("#div1 > #btn_1").on("click",function(){

		$inputval=$("#course_name > input").val();
		$("#statement > h3").text("Course Entered: "+$inputval).css("background-color","green");        
	});
    
    $("#courses").find("li").on("click",function(e){
            
        var $inputli=$("<li>"+$inputval+"</li>");
        $inputli.css({"background-color":"yellow"});
    	$(this).after($inputli);
        e.stopPropagation();  
    });

});

Hello campers !!. I am having a difficluty in understanding the difference between append and after methods of jquery. This is a small program in which after clicking every “li” element there should appear a “li” of input text which will be with a background of yellow. The input text will have background of green color after clicking “addcourse” button. The problem is with the behaviour of append and after. If I use append it works fine. Clicking every “li” will give us another “li” of added course preceded by clicked “li”. If I use after method what happen is if for example I input text of “My Course” than I clicked “Sociology”, a “li” will be added after it. But if I again click newly added li “My Course”, no “li” is again adding up after the clicked “li”. And if I click a “li” in nested “ul” for example “Algebra” I will have the added “li” of “My Course” right after “Algebra”, and this time if I click the newly added “li” i.e "My Course, a “li” will be added but not right after the clicked “li” but AFTER the whole nested “ul” which is “Mathematics”…The motive is whenever we click any “li” there should be a “li” added right after it with background color “yellow”. Just replace the after method with append if u wanna know how the program should work.


#2

.append() will always insert the new element(s) at the end of the nodelist. .after() can be given any element in the list to be inserted immediately after.


#3

Yeah I know this. Append inserts inside the element while After inserts right after that element. But using after should also be working but its not…


#4
$('ul').append(`<li>will be at the end of the list</li>`);

Whereas,

$('ul').eq(0).after(`<li>will be inserted after first item in the list</li>`);

Edit

Working on a better example. The above was off the top of my head, and does not work as expected. Bear with me while I rethink…

$('li').eq(0).after(`<li>will be inserted after first item in the list</li>`);

https://repl.it/OGro


#5

Sir you are telling me the difference between append and after. I know this all. For example we click “Sociology” a new “li” is added if we inspect element in dev tools the new “li” will also be as other “li”’ elements. But clicking the new “li” do nothing. And if the newly added “li” is in nested “ul” element i.e"Mathmatics" and we click it, it adds “li” but after the “ul” making it sibling of other outermost “ul” 's “li”. I mentioned what the program shoul do. Just replace the append method with after in my code to see how the program should work


#6

What this sounds like is an event listener attachment that is not happening. Suggest using event delegation so the list is dynamic and can have elements added and taken away at liberty.

$('ul').on('click', 'li', callback);

Example of delegation…

https://repl.it/Nz1F/0

There are no images but if youl hover on a thumb it’s tooltip will display. Click and then hover on the viewer. The tooltip will display, which indicates the attributes have been reassigned.


#7
$(function(){
var $inputval;
$("#div1 > #btn_1").on(“click”,function(){
$inputval=$("#course_name > input").val();
$("#statement > h3").text("Course Entered: "+$inputval).css(“background-color”,“green”)
});

$("#courses").find(“li”).on(“click”,addIt);

function addIt(e) {
var $inputli=$("<li>"+$inputval+"</li>");
$inputli.css({“background-color”:“yellow”});
$inputli.bind(“click”, addIt);
$(this).after($inputli);
e.stopPropagation();
}
});

This is a answer to me by someone and the reason he gave why my code is not working is that my code only runs once, so the click event is attached to existing li elements. With my version, I bind the same click event handler to the $inputli which is then put after the current li element being clicked. Without binding the click event to it at it’s creation, it does not have a click event to make the new li element respond to a click.

Still doesn’t satisfy meStrange. Because in dev tools it appears as other li elements. And click event is on all “li” elements. So if that’s the case as you are saying why if we click newly added “li” in nested “ul” elements will trigger the click event even though it is putting the newly added “li” at the wrong position. Newly “li” elements in nested “ul” should also be not doing anything according to his logic?


#8

We’re still guessing since we cannot see your code. Please post the HTML and the JS. Thanks.


#9

Sir, I posted it. Here it is again:

<!DOCTYPE html>
<head>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
  <body>

    <h1>Course Catelog</h1>
    <h3>Below is a list of course offerings to choose from</h3>

    <div id="course_name">
        <input type="textbox"></input>
    </div>
    <div id="div1" class="div_next">
        <button id="btn_1">Add Course</button>
    </div>
    <div id="statement">
        <h3></h3>
    </div>
    <div>
        <p>Below is a list of all the available courses <br>
        that can be enrolled in this semester:
        </p>
    </div>
    <ul id="courses">
      <li>Sociology</li>
      <li>Psychology</li>
      <li>Mathematics
        <ul id="math_subjects">
        <li>Algebra</li>
        <li>Geometry</li>
        <li>Calculus</li>
        </ul>
      </li>
      <li>Sciences
          <ul id="science_subjects">
          <li>Geology</li>
          <li>Physics</li>
          <li>Chemistry</li>
          </ul>
      </li>
      <li>World History</li>
    </ul>

        <script src="js/jquery-3.1.1.min.js"></script>
        <script src="js/custom_jquery_code.js"></script>

  </body>
</html>
.div_next {
    display: inline-block;
}

$(function(){

       var $inputval;
	$("#div1 > #btn_1").on("click",function(){

		$inputval=$("#course_name > input").val();
		$("#statement > h3").text("Course Entered: "+$inputval).css("background-color","green");        
	});
    
    $("#courses").find("li").on("click",function(e){
            
        var $inputli=$("<li>"+$inputval+"</li>");
        $inputli.css({"background-color":"yellow"});
    	$(this).after($inputli);
        e.stopPropagation();  
    });

});

#10

Must have a brain blockage. D’oh!


#11

Yeah you mentioned the same problem yesterday and I was like “What cant he see my code” :stuck_out_tongue:


#12

Briefly describe the key page elements. From the early part I deduce the user is adding a course name to the list, which action takes place once the button is clicked. That much I must have correct, right?

As for the list and being able to click it, what would be the action that follows that event?


#13

After clicking every “li” element a new “li” element should be added right after the clicked “li”. The action can be on any “li” whether the newly created or the old ones.


#14

https://repl.it/OGro/1

Run and when the list appears, click any element.


#15

Yeah but why it no works in my code ? I dont see any mistake in mine :confused:


#16

Sorry, I’ve been off in explorer land testing ideas. Here is a snippet that works on sub lists, too.

https://repl.it/OGro/2

Click any element.

I’ll take a closer look at your code, but expect me to refactor it in the end. For one, the HTML has way too much structure. I would reduce that significantly. But for now I’ll focus on getting your code to work. Back in a few moments…


#17

Solved.

https://repl.it/OGwf

$(function(){
  var $inputVal;
    $("#btn_1").on("click", function(){
    $inputVal = $("#course_name input").val();
    $("#statement h3").text(`Course Entered: ${$inputVal}`).css("background-color", "green");        
  });
    
  $("#courses").on("click", 'li', function(e){
    var $inputli = $(`<li>${$inputVal}</li>`);
    $inputli.css({"background-color": "yellow"});
    $(this).after($inputli);
    e.stopPropagation();  
  });
});

#18

Great But still why my code was not working. I noticed you just chnaged the selector line on which the click event should work. “$(”#courses").on(“click”, ‘li’, function(e){". My code was also finding all the li elements in courses and then I get click event on those “li”. So whats the solid base reason of my code not working. I wanna know the reason so I can refrain from it in future.


#19

The main issue was the event bindings on new list items. find() does not mix with delegation, that is what the second argument is for in the .on() listener.

As promised, I have refactored your code.

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Course Catalog</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <h1>Course Catalog</h1>
    <h3>Below is a list of course offerings to choose from</h3>

    <div id="add-course">
        <input type="textbox">
        <button>Add Course</button>
        <h3></h3>
    </div>
    <div>
        <p>Below is a list of all the available courses that can be enrolled in this semester:</p>
    </div>
    <ul id="courses">
      <li>Sociology</li>
      <li>Psychology</li>
      <li>Mathematics
        <ul id="math_subjects">
        <li>Algebra</li>
        <li>Geometry</li>
        <li>Calculus</li>
        </ul>
      </li>
      <li>Sciences
          <ul id="science_subjects">
          <li>Geology</li>
          <li>Physics</li>
          <li>Chemistry</li>
          </ul>
      </li>
      <li>World History</li>
    </ul>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="index.js"></script>
  </body>
</html>
$(function(){
  const bgG = {'background-color': 'green'};
  const bgY = {'background-color': 'yellow'};
  var $newCourse;
  
  $("#add-course button").on("click", function(){
    $newCourse = $(this).prev().val();
    $(this).next().text(`Course Entered: ${$newCourse}`).css(bgG);        
  });
    
  $("#courses").on("click", 'li', function(e){
    $(this).after(`<li>${$newCourse}</li>`);
    $(this).next().css(bgY);
    e.stopPropagation();  
  });
});

https://repl.it/OGwf/3


#20

Well. yeah, still I am not satisfied with not having a solid reason why click event doesn’t work on newly added li in my code, But anyhow really appreciate ur help, sir. Thanks