Copy/Clone div content to another div - javascript

I need to copy content from div1 and paste/append it to div2 by click. Then if I change content in div1 and click the button again the content should go to div3 without changing the content in div2. This is what I found so far.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="$('#div2, #div3').html($('#div1').html());">Copy</button>
<div id="div2"></div>
<div id="div3"></div>
Because I assign value it would paste the same in both divs and I have no idea how to do it separately. I guess some loops will be needed.
Is it possible and if it is could somebody give me some ideas or links to read materials. Thanks in advance!

You can use a variable to store the number of the div element and then increment it accordingly. (Here I am assuming only div2 and div3 are there)
Since you have not mentioned how the value of div1 is going to update. I am manually doing it using $('#div1').html("New Value"); inside the function add().
<html>
<body>
<body>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="add()">Copy</button>
<div id="div2"><p>div1 Placeholder</p></div>
<div id="div3"><p>div2 Placeholder</p></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var n = 2;
function add(){
$('#div'+n).html($('#div1').html());
$('#div1').html("<p>New Value</p>");
n++;
}
</script>
</body>
</html>
Try running the snippet. Clicking the button once will put the value of div1 to div2 and then it changes the original content of div1 to New Value. Again if you click the button, the new value of div1 i.e., New Value will be put to div3.
Though this will also try to update div1 again to New Value, which won't make any change. It would be better if you write some other ways to update the div1 element.
Take care of the <p> tag if you want it to be retained. Well, that also depends on the way you update the value of div1.
To append you can use $('#div'+n).append($('#div1').html());

I wrote a little help code to get you started. So what i did was to move the logic to a function which iterate a variable i (which can only take the value 2 and 3). This does not check if the text has changed and will overwrite div2 and div3 in turns on every click (remove if test if you only want to do it once).
<html>
<body>
<body>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="copyPaste()">Copy</button>
<div id="div2"></div>
<div id="div3"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
var i = 2;
function copyPaste() {
//add logic to check if text has changed before executing next line
$(`#div${i++}`).html($('#div1').html());
if(i < 3) i = 2;
}
</script>
</body>
</html>

Using a script tag with javascript code as in Saif's answer is perfectly valid (you only should be careful not to overwrite the global var used to keep count). To be more inobtrusive the click event could also be added in the script tag.
As another possibility with the opposite approach, you could do all in the the button attributes, using jQuery's data. The count is here stored in an attribute in the button, but it could also be stored in the original div #div1. The code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<p>Hello world</p>
</div>
<button onclick="$('#div' + $(this).data('targetdiv')).html($('#div1').html()); $(this).data('targetdiv', $(this).data('targetdiv') + 1);" data-targetdiv="2">Copy</button>
<div id="div2"></div>
<div id="div3"></div>
Some important notes about data: using data to change the value doesn't update the DOM attribute itself, because once the value is retreived from the attibute, jQuery uses an internal javascript code to keep the value. There's no real need to udate the DOM, but if you really want it to, you can use attr instead of data. But if you use attr, never mix it with calls to data, as the latter won't see the DOM updates after the first time it has retreived the value (because it uses the value stored in the internal javascript cache instead of reading the DOM attribute).

Related

Why won't all the ids get changed though I selected all of them by using the # idname?

I am completely new to coding in general. I've started with the very basics of HTML, CSS and JavaScript.
I have two paragraphs:
<p id="title1">Change this</p>
<p id="title1"> Change this too! </p>
While the first one gets automatically changed by:
<script type="text/JavaScript">
$('#title1').html('Changed!');
</script>
the second one doesn't. But shouldn't it? Since all #title1 are being changed?
I have the same problem for the onclick version. The first paragraph gets changed when clicking on it, the second doesn't.
<p id="title3" onclick="sayGoodbye();">Toggle this Hello - Goodbye</p>
<p id="title3" onclick="sayGoodbye();">Thing to click on</p>
<script type="text/javascript">
function sayGoodbye(){
$("#title3").html('Goodbye');
$("#title3").click(function(){
$("#title3").html("Hello again!");
$("#title3").off("click");
});
}
</script>
When you select an element by its id, only the first one gets selected because you're only supposed to use one id on one element! Each id should only ever be used once on a page!
If you need to get a bunch of elements together 'by' something, do it 'by class'.
$(".title1").html("Changed!");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="title1">Change this</p>
<p class="title1"> Change this too! </p>
ID attribute has to be unique for each HTML tag. You can use class attribute to act on multiple tags.
The id attribute should be unique at least in the same level child tree.
Use class instead and listen to .click() with $(this) to get
current clicked element.
If you want to call a function using onclick attribute pass clicked element to it using this like onclick="sayGoodbye(this);".
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="title3" onclick="sayGoodbye(this);">Toggle this Hello - Goodbye</p>
<p class="title3" onclick="sayGoodbye(this);">Thing to click on</p>
<script type="text/javascript">
function sayGoodbye(t){
$(t).html('Goodbye');
$(t).click(function(){
$(this).html("Hello again!");
$(this).off("click");
});
}
</script>

Why can't I retrieve "this" dom element without onclick?

I have a very basic question about using the "this" keyword to retrieve a DOM element.
Consider the following HTML/Javascript:
<div class="container">
<div class="regular-div">
<script type="text/javascript">
console.log(this);
</script>
Here is a div withOUT onclick
</div>
<div class="onclick-div" onclick="console.log(this)">
Here is a div with onclick
</div>
</div>
While clicking the "onclick-div" it does return the DOM object for that div. However, the console.log event calls 'this' indirectly in the "regular-div" and returns window.
Is it possible to get "this" DOM object when 'this' is called indirectly? My purpose is I want to fire a function in line in the HTML, but need to send the function "this". Here's an example of what i'm trying to do:
<div class="container">
<div class="regular-div">
<script type="text/javascript">
loadSomeHTML(this, varA, varB, varC);
</script>
</div>
</div>
Thanks everyone for any clarification of how "this" works in the above context.
In your first example, the script isn't in any way associated with the div. It's just been output within the div, but it's not connected to it. The script runs as the page is being parsed.
Is it possible to get "this" DOM object without a user interaction?
If you mean inline with the parsing of the HTML, you could do this:
<div class="container">
<div class="regular-div">
Here is a div withOUT onclick
</div>
<script type="text/javascript">
(function() {
var list = document.querySelectorAll('div');
console.log(list[list.length - 1]);
})();
</script>
</div>
Note that the script tag is immediately after the ending </div> tag for the div you're trying to target. The script gets what's currently the last div in the document as of when the script runs. Or of course you could identify the div in some way (a class, for instance) and use that (and then potentially remove it so you could do it again later in the document).
It looks dodgy, but it's perfectly valid cross-browser, and was even recommended at one stage by the Google Closure Library engineers.
Live Example:
<div class="container">
<div class="regular-div">
Here is a div withOUT onclick (look in console for result)
</div>
<script type="text/javascript">
(function() {
var list = document.querySelectorAll('div');
console.log(list[list.length - 1]);
})();
</script>
</div>
Example using a class we move:
<div class="container">
<div class="target-me">
The first div
</div>
<script type="text/javascript">
(function() {
var div = document.querySelector(".target-me");
div.classList.remove("target-me");
console.log(div);
})();
</script>
<div class="target-me">
The second div
</div>
<script type="text/javascript">
(function() {
var div = document.querySelector(".target-me");
div.classList.remove("target-me");
console.log(div);
})();
</script>
</div>
Note I didn't use id, because if we used an id and JavaScript wasn't enabled, we'd end up with an invalid document (because it would have multiple elements with the same id). It'd be fine if JavaScript were enabled (because we'd remove the id from earlier ones before later ones were created), but...
Javascript has no implicit connection to the HTML DOM. The reason why onclick works the way you want is because the HTML DOM implementation passes the element to the js callback. You need to do something similar in your other case. One way to do this is:
<div class="container">
<div class="regular-div" id="mydiv">
<script type="text/javascript">
loadSomeHTML("#mydiv", varA, varB, varC);
</script>
</div>
</div>
Then your js implementation does the lookup to find the element:
function loadSomeHTML(selector, varA, varB, varC) {
var el = document.querySelector(selector);
// now el is where you want to insert your HTML
// ...
}
The code inside the script tag doesn't have any connection with the tag itself. this should, basically, return the object on which the current function was called, or the global environment, window. In the first div, the code is just executed, on no object, so window is returned. The value of onclick, on the other hand, is treated as a function (with even some parameters, like e), that gets called on the element with the attribute. So, the code in the script element is executed in the global scope, whereas the one in the attribute is in a function scope (that's why all vars are shared across script tags).
As explained in How may I reference the script tag that loaded the currently-executing script?, the proper way of obtaining a reference to the script element whose code is being executed is
document.currentScript;
Then, to get the parent node of that element, use
document.currentScript.parentNode;
<div class="container">
<div id="regular-div">
<script type="text/javascript">
alert('#' + document.currentScript.parentNode.id);
</script>
Here is a div withOUT onclick
</div>
</div>

innerHTML replaces whole document

I have a setInterval function which replaces text within a particular div element every second. I also have text in the body which I want to keep.
What is the easiest way to preserve the text in a document without .innerHTML overriding the whole document?
<html>
<div id="timer" </div>
<script>
window.onload = setInterval(function(){refreshTime()},1000);
function refreshTime()
{
document.getElementById("timer").innerHTML = ""+DAYS+" Days:"+HOURS+" Hours:"+(minutes)+" Minutes:"+seconds+" ;
time = time+1;}
</script>
<body>
<p>
sOME TEXT I WANT TO KEEP ON
</p>
</body>
I've removed a lot of unncessary code to make it easier for you guys to read. I hope you guys understand what I'm asking. This is my first time on SO
<div id="timer" </div>
change it to <div id="timer"></div>
And paste it in body tag

How to get a value from div without write some event (onclick,etc) using jquery

I have some question about how to get some value from some element like div,etc using jquery and without write onclick event or etc on the div where I want to get that value.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="test" title="test1">test</div>
<div id="test2" title="test2">test2</div>
<script>
function getVal(attr,value){
$("#show").text("this "+attr+" have value ="+value);
}
$(document).ready(function(){
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
});
</script>
<div id="show"></div>
</body>
</html>
Usually to get some value from div that i click, I add an onclick event on div like
<div id='test' onclick="getVal(test)" ></div>
and it will return "test". And the code that I write above nearly what I want, but the problem that I have is if I have a many div, how can I get the value from each div that I click just using jquery click function and I don't need to write
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
$("#test2").click(function(){
getVal("#test2",$("#test2").attr("title"));
});//and so on
here the code that I use to achieve what I want, using onclick event that I put on div:
<script type="text/javascript">
function overlay(rel){
var value = rel;
$(document).ready(function(){
$(".img"+value).click(function(){
$(".overlay-bg"+value).fadeIn();
});
$(".close"+value).click(function(){
$(".overlay-bg"+value).fadeOut();
})
});
}
</script>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-a.jpg" class="img1" onclick="overlay(1)" title="photo1" alt="photo1"/>
</div>
<div id="overlay-bg" class="overlay-bg1">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/a.jpg"/>
<span>photo1</span>
<span style="font-size:0.8em;"><p>photo a</p></span>
<div id="close" class="close1"></div>
</div>
</div>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-b.jpg" class="img2" onclick="overlay(2)" title="photo2" alt="photo2"/>
</div>
<div id="overlay-bg" class="overlay-bg2">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/b.jpg"/>
<span>photo2</span>
<span style="font-size:0.8em;"><p>photo b</p></span>
<div id="close" class="close2"></div>
</div>
</div>
I'm really want to know how to resolve my problem.
Give the elements you want to attach the click event handler to the same class. Then use the class selector [docs] to select all of them:
$('.sharedClass').click(function() {
getVal(this.id, $(this).attr("title"));
});
jQuery will bind the event handler to each of the selected elements.
There are many ways to select elements [docs], selection by ID or class are just two of them. You might also find the jQuery tutorial useful to get a better idea of how jQuery works.
you can use the this keyword within the handler function, and it will point to the element that was clicked
Here's the correct way to do it.
Put a class name to your target div e.g.
<div id="test" class="clickable" title="test">test</div>
<div id="test2" class="clickable" title="test">test</div>
...
...
Then create a jQuery event with selected class
$('.clickable').click(function(){ ... });
<div id="test">harsh</div>
<script>
alert(document.getElementById('test').innerHTML);
</script>
If you want to call this function with the click of every div, use :
$("div").click(function(){
getVal($(this),$(this).attr("title"));
});
If you want to call the function for a set of divs, but not all, give those divs a class name as suggested by #Felix Kling.
Check out the jQuery Selectors to get a better idea.
Not sure what you're trying to achieve.
If you have multiple values how do you want to store them?
If you have an array that you wanted to populate you can use the each() function on a JQuery selector to traverse all elements selected.
Like so:
var values = new Array();
$(document).ready(function(){
$('#test1, #test2').each(function(){
values.push($(this).html());
});
});
You could also store the values in an associative way to make retrieval a bit easier if you didn't want to iterate through an array. For example you could use the value of the 'title' attribute as the key in the array.
Replace the values.push() line with this line of code:
values[$(this).attr('title')] = $(this).html();

Is my text indexed by Google?

I am making a HTML page, with JavaScript. In the HTML is the first content of a div, but when the user clicks a button, the text changes.
The text in the div is actual content, and needs to be findable by Google. The text is now stored in a simple variable in the JavaScript file.
Questions:
- Is that text indexed?
- Are there any better ways to store the text?
You can keep the text in a div and then change the visibility to hidden
<div id="content" style="visibility: hidden;">
Div content
</div>
Then in javascript,
document.getElementById("content").style.visibility="visible";
should make the document visible. Since the text will be there in the source for the page, it will be indexed by google, but will be displayed only when you run that line of javascript.
Storing the text in js variables is generally not a good idea.
You can put this text in a hidden div instead, like this:
<div id="target">
super-text
...
</div>
<div id="second">
super-mega-text
...
</div>
<button onclick="replace_text();">
<script type="text/javascript">
function replace_text() {
var target = document.getElementById('target');
var second = document.getElementById('second');
target.innerHTML = second.innerHTML;
}
</script>
In that case your second text will be indexed by Google.
Of course you better use any js framework like jQuery or Mootools.
Mootools example:
<div id="target">
super-text
...
</div>
<div id="second">
super-mega-text
...
</div>
<button id="button">
<script type="text/javascript">
window.addEvent('domready', function(){
$('button').addEvent('click', function(){
$('target').set('html', $('second').get('html'));
});
});
</script>
Javascript is not searched, see googles answer:
http://www.google.com/support/customsearch/bin/answer.py?answer=72366
I found a good article about hide/display content only with CSS. It's working without Javascript: http://www.devinrolsen.com/css-hide-and-display-content/

Categories

Resources