-1

my question is that I am using jQuery in JavaScript and using detach and append. Here is my JavaScript append and detach script.

var example1 = $(".example1").detach();
var example2 = $(".example2").detach();

showexample2();

$("#blue").click(function(){
    alert("hi");
    showexamples2();
    hideexamples1();
});


$("#red").click(function(){
    hideexamples2();
    showexamples1();
});



function hideexamples2(){
    $(".example2").detach();
}

function showexample2s(){
    $("body").append(example2);
}

function hideexamples1s(){
    $(".example1").detach();
}

function shoexamples1s(){
    $('body').append(example1);
}

However when red is clicked it ends up below the JavaScript and therefore has no functionality. enter image description here

How can I fix this?

Andreas
  • 21,535
  • 7
  • 47
  • 56
Tortoise41
  • 35
  • 5
  • You need to use proper method if you need to add the element somewhere else, read [`.append()`](https://api.jquery.com/append/) and [`.prepend()`](https://api.jquery.com/prepend/) documentation. – Mehdi Dehghani Jan 31 '22 at 19:03
  • The snippet editor has four parts. Each with a "name"/description what goes into it in the upper right corner. Why did you put the JS part in the HTML section? And where's the markup? – Andreas Jan 31 '22 at 19:03
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) -> _"**DO NOT post images of code, data, error messages, etc.** - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text."_ – Andreas Jan 31 '22 at 19:06
  • Also you need to read this question [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Mehdi Dehghani Jan 31 '22 at 19:07

1 Answers1

1

You are appending the element to the body. Which means it is being appended at the end of the body tags content. Use a explicit selector if you want to append it elsewhere like and ID or a class.

$('#elementToAppendTo').append(example1);

EDIT: Took me a while to understand the second half of your request. For the appended element to respond to events you need to attach the event listener on the parent. So that the event bubbles up through the DOM stack and your click event fires.

$("body").on("click", "#blue", function(){
    alert("hi");
    showexamples2();
    hideexamples1();
});

$("body").on("click", "#red", function(){
    hideexamples2();
    showexamples1();
});

This way your events will work even when you remove and re-add the DOM elements. I recommend consulting the jQuery documentation further.

EDIT:
To further iterate I recommend not putting script tags with code like that, put your javascript in an external file, and reference to it via a script source tag.

Jan
  • 115
  • 1
  • 12