I am using a code in which it inserts a text containing the url of the current page after the person copies the selection (ctrl-c) and does this in a hidden part of the page, however when the person presses ctrl-c the selection some, would you have some way to copy and include the url of the current page without losing the selection? Sorry for the english, it was translated via google translator
<!DOCTYPE html>
<html>
<head>
<script>
function addLink() {
//Get the selected text and append the extra info
var selection = window.getSelection(),
pagelink = '<br /><br /> Read more at: ' + document.location.href,
copytext = selection + pagelink,
newdiv = document.createElement('div');
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
//insert the container, fill it with the extended text, and define the new selection
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext.replace(/\n/g, "<br />");
selection.selectAllChildren(newdiv);
//remove a novadiv
window.setTimeout(function () {
document.body.removeChild(newdiv);
}, 100);
}
document.addEventListener('copy', addLink);
</script>
</head>
<body>
<div id='perg'>Text to copy</div>
</body>
</html>
Not sure this is what you want. I actually created a div (displayed) that is just static and not dynamically created like you have for demo purposes. If I understand correctly you want to keep the current selection selected while copying the text and the location href to that div ? If you want the text you actually can use .toString(), and in your code, when you use selection.selectAllChildren you are deselecting the text that you copied from. Hard to undestand really exactly what you are asking.
<!DOCTYPE html>
<html>
<head>
<script>
function addLink() {
let hiddendiv = document.getElementById('copiedstuff');
let selection = window.getSelection();
let selectiontext = window.getSelection().toString();
pagelink = '<br /><br /> Read more at: ' + document.location.href;
copytext = selectiontext + pagelink;
hiddendiv.innerHTML = copytext.replace(/\n/g, "<br />");
}
document.addEventListener('copy', addLink);
</script>
</head>
<body>
<div id='perg'>Text to copy</div>
<div id='perg1'>Something Else</div>
<div style = "margin-top:20px;border:1px solid black;">
<div id='copiedstuff'></div>
</div>
</body>
</html>
Related
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="data_generator.js"></script>
<title> Twiddler </title>
</head>
<body class='box'>
<body>
<div class='container'>
<h1 class='title'>My Twiddler</h1>
<div class='main'>
<h2>Tweet Feed</h2>
<p class='tweets'></p>
<p class='new'></p>
<button class='button'>New Tweets</button>
</div>
</div>
<script>
$(document).ready(function(){
var $body = $('.main');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<p></p>');
$tweet.text('#' + tweet.user + ': ' + tweet.message + tweet.created_at);
$tweet.appendTo('.tweets');
index -= 1;
}
//show new tweets using button
var $button = $('.button');
$button.click(function() {
//get random tweet
//streams.home is an array of all tweets of all users
var tweet = streams.home[Math.floor(Math.random() * streams.home.length)]
var $tweet = $('<p></p>');
$tweet.text('#' + tweet.user + ': ' + tweet.message + tweet.created_at);
$tweet.appendTo('.tweets');
})
//click on user to see tweet history
$body.click(function() {
})
//styling
$('.box').css("background-image", "url('https://www.rightmixmarketing.com/wp-content/uploads/2016/04/Twitter-Background.png')");
$('.title').css('font-size', '40px').css('text-align', 'center');
$('h2').css('text-align', 'center');
});
</script>
</body>
</body>
</div>
</html>
I'm making a twitter look a like. I am trying to show a users history by being able to click on the username and displaying all current tweets. How can I go about and do this? I have it set to click on the body of my text but obviously that is not the right way. How can I specifically target the username in this case? I attached a picture of my current html
How to register the event clicking just on 'username' part of the text?
Consider the following:
<p>
<a class='click-me' >Username</a>
There is a lot of text here.
There's some more text here. I want to be able to click ...
</p>
So you just need to wrap the username in an html element which has a certain class.
Then, you specify a listener for the click event on that class:
$('.click-me').on('click', function() {
//do something
});
Now, you probably need to know which username we're talking about and how to get the specific posts, for that there are other solutions. But this one answers your question in specific.
I'm sorry if this is too simple of a question. I am trying to change all instances of & to and using the event-handler blur. I am seeming to get no changes on blur even if my function is simply
id.value = "Random test string";
so I am assuming this is a problem with the event handler itself. Any help would be appreciated, thanks.
I have the code for changing & commented out because I was checking to see if the function tied to the blur eventhandler was triggering at all, which it was not. This code also has an HTML file with a text box with an ID of textid
<script type="text/javascript">
//var for saving the string
var textvar;
//var for the texta area
var id = document.getElementById("textid");
id.addEventListener("blur", function() {
//textvar = id.value;
//textvar = textvar.replace("&", " and ");
//id.value = textvar;
textvar = "Correct!!";
id.value = textvar;
}, false);
</script>
This code is working fine and as expected:
<input type="text" id="textid" />
JS Code
//var for saving the string
var textvar;
//var for the texta area
var id = document.getElementById("textid");
id.addEventListener("blur", function() {
textvar = id.value;
textvar = textvar.replace(/\&/g, " and ");
id.value = textvar;
}, false);
You can find the working Pen here
You might want to consider this other approach:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function change(element) {
let textvar = element.value;
if (textvar.indexOf('&') !== -1) {
textvar = textvar.replace("&", " and ");
}
element.value = textvar;
}
</script>
</head>
<body>
<input type="text" onblur="change(this)" />
</body>
</html>
I hope this could help.
I'm a beginner in javascript and I have a little problem with my code. I found an exercise and i'm trying to do it. I have to write a function that will insert text from variable into table. I never met something like this. This variable looks like four objects in array. I want to show text in the table when I press a button. There are two buttons. When I press "Fizyka" button i should see:
Fizyka
Ola Kowal
Ela Nowak
and when I press "Chemia":
Chemia
Ala Goral
Ula Szpak
So this is my code. All i can edit is function show(study):
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
</head>
<body>
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"></div>
<script>
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
if (study==='fizyka')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
if (study==='chemia')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
}
</script>
</body>
</html>
It's not working. I don't know how to insert text from this variable into table.
There is several problem with your code. I have written piece of code which is working and you can use it and inspire.
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"><h2></h2><ul></ul></div>
<script>
//Student array
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
console.log('ENTER show('+study+')');
//Select h2 element
var header = document.getElementById("list").firstChild;
//Set h2 element text
header.innerHTML = study;
//Select ul element
var list = document.getElementById("list").lastChild;
//Set inner html to empty string to clear the content
list.innerHTML = "";
//loop through students and set the appropriate html element values
for(var i = 0; i < student.length; i++){
//check whether student[i] studies study which is put as a paramter into the function
if(student[i].study === study){
//Create new li element
var li = document.createElement('li');
//Into li element add a new text node which contains all data about the student
li.appendChild(document.createTextNode(student[i].name + ' ' + student[i].second_name));
//add li element into ul
list.appendChild(li);
}
}
console.log('LEAVE show('+study+')');
}
</script>
I am trying to get a feel for adding content to a page with XMLHTTPRequest. I would like to add the results to existing page content say in a second column, but I am not having any luck. I would appreciate a shove in the right direction. Thanks for any help.
<!DOCTYPE html>
<html>
<head>
<style>
#button{
float: left;
}
#team{
float: left;
}
</style>
<title>XMLHTTPRequest</title>
<script src="jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc = xhr.responseXML;
var team = xmlDoc.getElementsByTagName("teammember");
var html = "";
for (i = 0; i < team.length; i++){
html +=
xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue + "<br>" +
xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue + "<br>" +
xmlDoc.getElementsByTagName("bio")[i].childNodes[0].nodeValue + "<br><br>";
}
//this is the code I would like help with
var team = document.getElementById("team");
team.appendChild(document.createTextNode("html"));
}
}
xhr.open("GET", "team.xml", true);
});
</script>
</head>
<body>
<div id="button">
<button onclick="xhr.send()">Click Me!</button>
</div>
<div id="team">
</div>
</body>
</html>
I wrote a script fairly similar to yours that does nearly exactly what you are on about. Below is the some normal JavaScript I used to put it all on the page, I have changed some of the variable names so it compares nicely with your code.
for (i=0; i<team.length; i++)
{
//Create text nodes for each element as that's what appendChild() needs
var nameText = document.createTextNode(xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue);
var titleText = document.createTextNode(xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue);
var bioText = document.createTextNode(xmlDoc.getElementsByTagName("bio")[i].childNodes[0].nodeValue);
//This div will contain one team member's info
var memberDiv = document.createElement('div');
//Add text to the div created
memberDiv.appendChild(nameText);
//Line break
memberDiv.appendChild(document.createElement('br'));
memberDiv.appendChild(titleText);
memberDiv.appendChild(document.createElement('br'));
memberDiv.appendChild(bioText);
//Add the div we've just created to the document.
document.getElementById('team').appendChild(memberDiv);
}
This may need some more adapting to suit your needs but you get the general idea. This is just one way of doing it, there's probably loads of other ways including with jQuery that may be a bit neater actually.
You can use memberDiv.setAttribute('class', className) to set the class of each div to whatever you want
Below is a visual representation of this code to make it easier to understand, click for full scale (500*1750):
I have a function in javascript that I intend to use to create/add a link to a 'subLink' div, and add an onclick event to this link that loads associated 'content' to a contentDiv:
function addSubLink(text, name, content) {
// append programLink span to subLinks:
document.getElementById("subLinks").innerHTML += "<span class=\"programLink\" id=\"" + name + "\">" + text + "</span>";
// load program content onclick:
document.getElementById(name).onclick = function () {
// set value of programContent to content's value
document.getElementById("programContent").innerHTML = content;
}
}
This function would be called, for example, by loadAboutPage() to populate the subLink div
var whatContent = "<p>A website!</p>";
var whyContent = "<p>Recreation!</p>";
var howContent = "<p>Kludges.</p>";
addSubLink("WHAT", "whatLink", whatContent);
addSubLink("WHY", "whyLink", whyContent);
addSubLink("HOW", "howLink", howContent);
The problem is that only the last subLink has an onclick event attached to it (content is loaded and css class changed). That is, it creates WHAT, WHY, and HOW links, but only appends the onclick function to the last called: HOW, in this case.
I'm very rusty when it comes to JavaScript, so I have no idea if it's a result of my lack of knowledge about anonymous functions, or using the local 'name' variable incorrectly, or anything else completely different. I've searched for awhile, but it seems I'm too ignorant to even figure out what a similar problem would be!
Anyway, I greatly appreciate your help! Thanks in advance!
EDIT:
Here's a complete HTML example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Stack Overflow Example</title>
<script type="text/javascript">
function addSubLink(text, name, content) {
document.getElementById("subLinks").innerHTML += "<span class=\"programLink\" id=\"" + name + "\">" + text + "</span>";
document.getElementById(name).onclick = function () {
document.getElementById("program").innerHTML = content;
}
}
window.onload = function() {
var whatContent = "<p>A website!</p>";
var whyContent = "<p>Recreation!</p>";
var howContent = "<p>Kludges.</p>";
addSubLink("WHAT", "whatLink", whatContent);
addSubLink("WHY", "whyLink", whyContent);
addSubLink("HOW", "howLink", howContent);
}
</script>
</head>
<body>
<div id="container">
<div id="programWindow">
<div id="subLinks"> </div>
<div id="program"> </div>
</div>
</div>
</body>
</html>
The issue is due to:
....innerHTML += "...";
By setting innerHTML, all existing child elements are first removed, then the markup is parsed to create new elements. So, while the original "WHAT" and "WHY" spans did have onclick bindings, they've being replaced by similar elements that don't.
To append a new element and keep state, you'll want to use DOM methods like createElement(), appendChild(), and createTextNode() (or set textContent/innerText):
function addSubLink(text, name, content) {
var span = document.createElement('span');
span.className = 'programLink';
span.id = name;
span.appendChild(document.createTextNode(text));
// append programLink span to subLinks:
document.getElementById('subLinks').appendChild(span);
// load program content onclick:
span.onclick = function () {
// set value of programContent to content's value
document.getElementById("programContent").innerHTML = content;
};
}
Example: http://jsfiddle.net/bG7Dt/