How can I re-attach element with jQuery? [duplicate] - javascript

This question already has answers here:
Re-attaching jQuery detach();
(8 answers)
Closed 6 years ago.
Hey guys I am trying to re-attach an element when it has been detached from the DOM however I can't seem to find an easy solution to this.
$(document).on('click', '#emailEnquiryPreferred', function () {
$('.form-group-timepicker').fadeOut(300, function(){ $(this).detach(); });
});
As you can see with the following code I am detaching it however with another click event I would like to reattach it to the same position, how can this be done?
Thanks

Keep it as variable before attaching it:
var $detachedElement;
$(document).on('click', '#emailEnquiryPreferred', function () {
$('.form-group-timepicker').fadeOut(300, function(){
$detachedElement = $(this);
$(this).detach();
});
});
Now when you need to re-attach it simple use $detachedElement variable ...
Here is a full sample:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
var $detachedElement;
$(document).ready(function() {
$('#id2').on('click', function() {
$('#div').append($detachedElement);
})
$("p#id1").click(function() {
$detachedElement = $(this).detach();
});
});
</script>
</head>
<body>
<div id="div" style="border: red solid 1px">
<p id="id1">Detach Me!</p>
</div>
<p id="id2">Re-attach it!</p>
</body>
</html>

You can store detached element:
var p = $(this).detach();
You need to store this element somewhere (for example in some object):
var detachedObj = null;
$(document).on('click', '#emailEnquiryPreferred', function () {
$('.form-group-timepicker').fadeOut(300, function(){
if(detachedObj == null)
detachedObj = $(this).detach();
else
{
$(this).attach(detachedObj);
detachedObj = null;
}
});
});
You can see similar example in jQuery API Documentation for .detach() (read example part): jQuery .detach()

Related

addEventListener() with "click" can't run but no error show up to shuffle text with Chaffle.js

I'm having trouble with Chaffle.js library
I tried with jQuery and pure Javascript to add 1 more event is click to shuffle text when I click on a button with id="test" but they can't work and I don't see any errors show up in F12.
I hope you guys can help me.
Here is my code on Plunker
http://plnkr.co/edit/Yc8OrVW6QgVt0V6t
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chaffle#2.1.0/src/chaffle.min.js"></script>
</head>
<body>
<button id="test">Shuffle</button>
<h1 class="shuffle">This created for shuffle effect but it isn't work</h1>
<h3 data-chaffle="en">About Me</h3>
<script>
var elements = document.querySelectorAll("[data-chaffle]");
Array.prototype.forEach.call(elements, function (el) {
var chaffle = new Chaffle(el);
el.addEventListener("mouseover", function () {
chaffle.init();
});
});
document.querySelectorAll("#test").addEventListener("click", function () {
var elm = document.querySelectorAll(".shuffle");
Array.prototype.forEach.call(elm, function (el) {
el.dataset.chaffle ='en';
var chaffle = new Chaffle(el);
el.addEventListener("click", function () {
chaffle.init();
});
});
});
</script>
</body>
</html>
Thank you!!
there is maybe a bug in chaffle.js line 54
if (dataLang.length !== 0) data.lang = dataLang
its not check dataLang for null, so it required to adddata-chaffle attribute to the element
var elm = document.querySelectorAll(".shuffle");
Array.prototype.forEach.call(elm, function (el) {
el.dataset.chaffle ='en'; // <== append this

Local Storage error

Please someone tell me what is the problem in the code which i have written.
Js
$("button").click(function() {
document.getElementById("demo").innerHTML = document.getElementById("asd").value;
});
$(function() {
var edit = document.getElementById('demo');
$(edit).blur(function() {
localStorage.setItem("data1", this.innerHTML)
});
if (localStorage.getItem("data1")) {
edit.innerHTML = localStorage.getItem("data1");
}
});
Html
<input type="text" id="asd">
<button>asdsad</button>
<p id="demo"></p>
But the same code is working perfectly in this:
Js
$(function() {
var edit = document.getElementById('demo');
$(edit).blur(function() {
localStorage.setItem("data1", document.getElementById("demo").innerHTML)
});
if (localStorage.getItem("data1")) {
edit.innerHTML = localStorage.getItem("data1");
}
});
HTML
<div contenteditable="true" id="demo">Some text here</div>
Please some one tell me what went wrong here.
When you pass the edit variable (which contains a DOM element) into jQuery as an argument, a jQuery object is returned. That changes the scope of this inside your blur event to a jQuery object. jQuery doesn't have a property of innerHTML, so it returns undefined. JavaScript DOM elements do have an innerHTML property of course, so that's why the second example works.
One way to fix your first example is to replace this:
$(edit).blur(function() {
localStorage.setItem("data1", this.innerHTML)
});
With this:
$(edit).blur(function() {
localStorage.setItem("data1", $(this).html());
});

change the background of an id that is clicked

When one of the element(id) of a form is clicked, i would like to listen to that event, and change the background of that element.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$(x).css('background-color',color);
return false;
});
}
<form>
<div id="a">Item1</div>
<div id="b">Item2</div>
<div id="c">Item3</div>
</form>
Your code will end up looking for tag names because the selector is
$("b")
If you want to do it the way you have it, you would need to add the missing #.
$("#" + x).css('background-color',color);
But there is no need to look up the element when you already have a reference to is. Use event delegation and this
$('form').on('click', 'div', function(e){
$(this).css('background-color',color);
});
Why bother using e.target? Just update your code to use $(this):
$(function() {
$('form > div').on('click', function(e) {
e.preventDefault();
$(this).css('backgroundColor', color);
});
});
This will work out. Take care of your tags.
$(document).ready(function(){
$('form').on('click', function(e){
var x = e.target.id;
$("#"+x).css('background-color',"red");
return false;
});
});
The thing happening to you is that event.target.id returns a string representing the id of the element, not a selector. So where you use $(x).... you have to use $('#'+x), your actual code does not work because the selector for the background change is not looking for an element with the X value on the Id but for an element called like the value of X (eg. x="a", then it's looking for elements)
Here's my "lowly" try:
<!DOCTYPE html>
<html lang = 'es'>
<head>
<title> My Test </title>
</head>
<body>
<form>
<div id="a"> Item1 </div>
<div id="b"> Item2 </div>
<div id="c"> Item3 </div>
</form>
<script>
function addBackgroundColor(e){
var index = parseInt(Math.random() * 4); // the number of the multiplier has to be equal to the length of the array colorsList.
e.target.style.backgroundColor = colorsList[index];
}
var colorsList = ['blue','red','green','yellow','orange']; //add others colors here if you want.
var divsList = document.getElementsByTagName('div');
for (var i in divsList){
divsList[i].addEventListener('click', addBackgroundColor);
}
</script>
</body>
</html>
No need to go fancy. Just do
$(document).ready(function(){
$('form div').on('click', function(e){
$(this).css('background-color',color);
return false;
});
}

Javascript onclick event not working [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
On running below code, getting following error - "Uncaught TypeError: Cannot set property 'onclick' of null"
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("x").onclick = function() {
alert("clicked the button");
};
</script>
</head>
<body>
<button id="x">this is button</button>
</body>
</html>
You cannot get the element by id because the document is not loaded.
try to add onload function:
window.onload = function() {
document.getElementById("x").onclick = function() {
alert("clicked the button");
};
};
You're attempting to bind the click event before the button exists in the DOM. Either move your click event binding to the bottom of your body, of change it as follows:
<button id="x" onClick="alert('clicked the button');">this is button</button>
Cheers,
autoboxer
You need to set up an event listener:
var button = document.getElementById('x');
button.addEventListener('click', function() {
console.log('button clicked');
});
You need to migrate your <script> element after <button>. The error is thrown because getElementById returns null as it could not find the element #x as the button#x element had not been yet reached at that point of time.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="x">this is button</button>
<script>
document.getElementById("x").onclick = function() {
alert("clicked the button");
};
</script>
</body>
</html>

dynamically create element using jquery

I am trying to create element using jquery. When i click on a link, i want to create an element "p", give it some text, and then put it in one of my divs. Also, i want to check which link is clicked on, so i can put the created "p" in the right div. Any solutions on where i am doing it wrong?
Javascript/Jquery
$(document).ready(function () {
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
}
$("#menu").find('a').each(function () {
$(this).click(function () {
createElement();
});
});
createElement();
});
HTML
<html>
<head>
<title>Inl1-1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style-1.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="Uppg1.js"></script>
</head>
<body>
<ul class="meny" id="menu">
<li>Utvärdering/Feedback</li>
<li>Kontakt</li>
<li>Öppettider</li>
<li>Om Asperöd</li>
</ul>
<div id="contentl1">
</div>
<div id="contentl2">
</div>
<div id="contentl3">
</div>
<div id="contentl4">
</div>
</body>
</html>
Here is the best way to add new <p> element with text "Hej" to #contentl1 using jQuery:
$("<p />", { text: "Hej" }).appendTo("#contentl1");
function createElement() {
var a = $("#menu").find('a').each(function(){
if(a == "l1"){
var p = $("<p>");
p.text("Hej");
$("#contentl1").append(p);
}
});
}
For a start the click function can be done like this instead of having to use .find():
$('#menu a').click(function() { }
The .each() loop can be done like:
$('#menu a').each(function () {
var aId = $(this).attr('id');
var contentId = content + aId;
$(contentId).append('<p>Hej</p>');
})
I know it doesn't realate to answering your question but it is hard to leave this as a comment:
var a = $("#menu").find('a').each(function(){ <-- this "a" will only be created after the each completes
if(a == "l1"){ <-- this "a" that you are verifying is a global variable
var text = $(document.createElement('p');
$('p').text("Hej");
$("#contentl1").append("text");
}
});
You can try this to solve your issue:
function createElement() {
if($(this).attr("id") == "l1"){
$("#contentl1").append('<p>hej</p>');
}
}
$("#menu a").each(function () {
$(this).click(function () {
createElement.apply(this);
});
});
Something like this fiddle?
$('#menu').on('click', 'a', function(e) {
e.preventDefault();
$('<p>').text($(this).text()).appendTo('#content'+this.id);
});
try this script, it'll do place the text in correct div.
$(document).ready(function () {
$("#menu").find('a').each(function () {
$(this).on('click',function () {
$("#content"+$(this).attr("id")).append("<p>link "+$(this).attr("id")+" is clicked</p>");
});
});
});
I personally like to use classic JS DOM for tasks so this is how you can first create the DOM object using JQuery. The DOM object returned is the outer element of HTML (p tag) but the inner HTML can be as complex as you want.
var elP = $("<p>Hej</p>")[0]
// Do some other DOM manipulations of p
// eg: elP.someCustomTag='foobar'
$("#content1").append(elP)

Categories

Resources