How to add text when onmouseover is activated - javascript

<div id="first_caption">
<p style="float: left; clear: left">
<img
src="http://www.ottawaskeptics.org/images/stories/lightbulb.jpg"
onmouseover="this.src='http://pngimg.com/upload/small/bulb_PNG1251.png'"
onmouseout="this.src='http://www.ottawaskeptics.org/images/stories/lightbulb.jpg'"
height="50" width="50"
>
<p>How can you save money to do the things you love, and live a healthier life? rollover on the light bulb to see how!</p>
</div>
This is the code. what i am trying to do is make a text appear below the first paragraph when i hover over the image.

Add div or span, assign an ID and then on event add values to the ID.
var div = document.getElementById('divID');
div.innerHTML = div.innerHTML + 'Extra stuff';
here is the complete example:
click here
<div id="heading1">
This is existing text.
</div>
<script>
function myClick(){
text = "This text is added.";
document.getElementById('heading1').innerHTML = document.getElementById('heading1').innerHTML + text;
}
</script>

Related

Can’t set figcaption text as firstChild of figure

I can set the text of a figcaption if I access it by its ID (Line commented out in code below). However I can’t set it if I access the figcaption as firstChild of the figure. Why not?
<body>
<figure id="fig1">
<figcaption id="figcap1">Camberley Mail</figcaption>
<button type="button" id="thumb1" onclick="showBigImg (1);"></button>
<p>Text to go with picture.</p>
</figure>
<script>
"use strict";
function showBigImg(figNum) {
// let temp = document.getElementById("figcap" + figNum);
let temp = document.getElementById("fig" + figNum).firstChild;
temp.innerHTML = "some text";
}
</script>
</body>
</html>

Call previous sibling as function parameter?

I'm building a wee letter-writing tool that will have a range of paragraphs the user can choose to add to a letter, but I worry that I'm doing it in a really inefficient way.
Currently, it's structured like this:
<p id="deposit-dispute" class="paragraph">This is a paragraph about deposits not being protected</p>
<button onclick="addPara(depositDispute)" class="add">Add paragraph</button>
and then in the Javascript, I create a const that pulls the inner HTML of that id:
const depositDispute = "\n" + document.getElementById("deposit-dispute").innerHTML + "\n";
which the addPara() function then adds to the textarea:
function addPara(text) {
document.getElementById("text-body").value += text;
}
But would there be a way to make the function just call whatever the previous p element had in it, rather than having to give them all unique IDs and creating a unique variable for them all?
Here it is in a codepen so you can see what I'm trying to do - the paragraphs to be added are in the accordion on the right: https://codepen.io/gordonmaloney/pen/GRWyjOP
Thanks a lot - and big apologies if this is a ridiculously amateurish question, I've spent ages trying to google a solution but can't find a thing!
G
Each box contains a paragraph and a button.
We can get all the boxes and each box paragraph and button, and finally add click event to the button to insert the paragraph html of this box to the textarea
// Get textarea and boxes
var textarea = document.getElementById('textarea');
var boxes = document.querySelectorAll('.box');
// get the button and the paragraph of each box
boxes.forEach(box => {
var btn = box.querySelector('.button');
var paragraph = box.querySelector('.paragraph');
// add the html of the selected box paragraph to the textarea
btn.addEventListener('click', () => {
textarea.value += "\n" + paragraph.innerHTML; + "\n";
});
});
<div class="wrapper">
<div class="box">
<p class="paragraph">This is paragraph 1</p>
<button class="button">Add to textarea</button>
</div>
<div class="box">
<p class="paragraph">This is paragraph 2</p>
<button class="button">Add to textarea</button>
</div>
<div class="box">
<p class="paragraph">This is paragraph 3</p>
<button class="button">Add to textarea</button>
</div>
</div>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>

programmatically select part of content on another contenteditable div

<div id="leftdiv" style="float:left;display:inline-block;height:100px;font-family:Helvetica;font-size:14px;width:300px;border:1px solid red;" contenteditable>
<div>
first text
</div>
<div>
second text
</div>
...
<div>
other texts
</div>
</div>
<div id="rightdiv" style="margin-left:1em;display:inline-block;float:left;width:300px;height:100px;font-family:Helvetica;font-size:14px;border:1px solid red;" contenteditable>
<div>
first text
</div>
<div>
second text
</div>
...
<div>
other texts
</div>
</div>
I have two contenteditable divs and these divs have exactly the same content. When I highlight part of content in leftdiv like "ond" in "second" text using mouse, i want exactly the same part in rightdiv highlighted at the same time. Eventually 2 highlighting in seperate divs will occur simultaneously.
I have tried this but nothing happens.
$('#leftdiv').on('mousedown', function() {
$('#leftdiv').on('selectstart', function() {
document.getElementById('rightdiv').tabIndex = -1 ;
document.getElementById('rightdiv').focus();
var range = document.createRange();
range.selectNodeContents(this);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
});
});
This is far from a complete solution, and it makes use of css to fake the second selection, but perhaps it will give you an idea.
Try selecting "ond" in the leftdiv, as you suggested in your description, and "ond" is highlighted in the rightdiv (after the selection is complete - it won't live update as you drag the mouse to change the selection).
If you select content across multiple divs within leftdiv, this will break, and if you select text that appears multiple times, it will highlight the first match, not the exact match. Like I said, just trying to give you a potential path to explore further.
$('#leftdiv').on('mouseup', function() {
$("*").removeClass("highlight");
$('#rightdiv').html($('#leftdiv').html());
var selection = window.getSelection()+"";
var matchStart = $('#rightdiv').html().indexOf(selection);
var matchEnd = matchStart + selection.length - 1;
var beforeMatch = $('#rightdiv').html().slice(0, matchStart);
var matchText = $('#rightdiv').html().slice(matchStart, matchEnd + 1);
var afterMatch = $('#rightdiv').html().slice(matchEnd + 1);
$('#rightdiv').html(beforeMatch + "<font class='highlight'>" + matchText + "</font>" + afterMatch);
});
.highlight {background-color:#b4daf7;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="leftdiv" style="float:left;display:inline-block;height:100px;font-family:Helvetica;font-size:14px;width:300px;border:1px solid red;" contenteditable>
<div>
first text
</div>
<div>
second text
</div>
...
<div>
other texts
</div>
</div>
<div id="rightdiv" style="margin-left:1em;display:inline-block;float:left;width:300px;height:100px;font-family:Helvetica;font-size:14px;border:1px solid red;" contenteditable>
<div>
first text
</div>
<div>
second text
</div>
...
<div>
other texts
</div>
</div>

javascript-Replace one div(created dynamically) with other div(created dynamically) on click of button

I have buttons that are dynamically created , let say 5 buttons gets created button1, button2, button3, button4, button5. when I click on some button(let say, button1) a div(say div1) is created. And when i click on other button(say button2) another div(say div2) is created. I want to display one at a time. That is, when i click on button1 , div1 should be displayed and rest other div should not be displayed. But in my code when i click on button1, div1 gets created. And when i click on button2 div2 is appended. I want to replace div2 by div1.
I have tried using replaceWith() and checking for siblings also. But it didn't worked.
Here is my code:
javascript:
$(document).ready(function(){
var request = $.ajax({'url': '/FunctionName'});
request.done(function(response)
{
var output = document.getElementById('output');
response = JSON.parse(response)
response.forEach(function(item){
var button = document.createElement("input");
button.type = "button";
button.value = item[0];
button.name= item[0];
button.onclick = createDiv;
output.appendChild(button);
function createDiv() {
var div = document.createElement('div');
div.setAttribute("id", item[0]);
div.setAttribute("class","inner");
div.innerHTML = item[1];
showDiv.appendChild(div);
}
});
});
request.fail(function(jqXHR, textStatus)
{
alert('Request failed: ' + textStatus);
});
});
HTML:
<div id="regex_1" class="tab-pane fade">
<div id="output" class="panel panel-default" style="float:left; width: 30%" >
</div>
<div id="showDiv" class="panel panel-default" style="float:left; width: 70%" >
</div>
</div>
This is a simple replacement div code. Is your expectation?
$(".buttonShowDiv").on("click", function(){
$("#mainDiv .replaceDiv").replaceWith($(this).closest("div").find(".replaceDiv").clone());
$("#mainDiv .replaceDiv").show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="div1 replaceDiv" hidden="hidden">
<p>This is div 1</p>
</div>
<input type="button" class="buttonShowDiv" value="button 1"/>
</div>
<div>
<div class="div2 replaceDiv" hidden="hidden">
<p>This is div 2</p>
</div>
<input type="button" class="buttonShowDiv" value="button 2"/>
</div>
<div id="mainDiv">
<div class="replaceDiv">
<p>This is default div</p>
</div>
</div>
Add one more class to your divs like 'alldivs'.
So all of your divs will be hidden except for the one you are creating.
function createDiv() {
var alldives=document.getElementsByClassName('alldivs');
alldivs.display='none';
var div = document.createElement('div');
div.setAttribute("id", item[0]);
div.setAttribute("class","inner alldivs");
div.innerHTML = item[1];
showDiv.appendChild(div);
}
This way you can hide all of other divs that you have created before and only show to current one.

Swapping text of parent and child elements

I have the following elements:
<div contenteditable="true" id="write">
<div class="tooltip">
<span>test</span> <!--text to be written in text area-->
<span class="tooltiptext"> <!--holds words to be displayed on hover-->
<span class="popUpWord">hello</span>
<br>
<span class="popUpWord">dog</span>
</span>
</div>
<div class="tooltip">
<span>test</span>
<span class="tooltiptext">
<span class="popUpWord">hello</span>
<br>
<span class="popUpWord">test</span>
</span>
</div>
</div>
These basically show a pop-up similar to the following - http://www.w3schools.com/css/tryit.asp?filename=trycss_tooltip
On hover event of elements having the '.tooltop' class (words to be displayed inside the pop-up area), I would like to swap the word which is hovered in the pop-up area, with the word displayed in the text area after a couple of seconds.
I did the following function:
//--choosing word from pop-up list--//
$(document).on("mouseover", ".popUpWord", function(e)
{
if(!timeoutId)
{
timeoutId=window.setTimeout(function()
{
timeoutId=null;
e.currentTarget.innerHTML = e.fromElement.parentElement.parentElement.childNodes[0].childNodes[0].innerText;
/*not working*/ e.fromElement.parentElement.parentElement.childNodes[0].childNodes[0].innerHTML = e.currentTarget.innerHTML; //Although the elements I want to swap are referred to correctly,the element's text is not changing. (Tried using innerText)
},1500);
}
}).on('mouseout', '.popUpWord', function(e)
{
if(timeoutId)
{
window.clearTimeout(timeoutId);
timeoutId=null;
}
});
However, in the line marked not working - the element's text is not changing. And it is being referred to correctly.
Any help is greatly appreciated.
Thanks
Its because you are assigning the value of tooltip to the text element and re-assigning it to the tooltip.
Try this:
timeoutId=null;
var text = e.currentTarget.innerHTML;
e.currentTarget.innerHTML = e.fromElement.parentElement.parentElement.childNodes[0].childNodes[0].innerText;
e.fromElement.parentElement.parentElement.childNodes[0].childNodes[0].innerHTML = text;
You are trying to locate the source and destination elements in a way that can only lead to brittleness and errors. Give elements you know you want to work with ids and reference them that way.
Try this out. Hover over "helo".
var orig = $("orig");
var hold = $("hold");
var timeoutId = null;
$(".popUpWord").on("mouseover", function(e){
if(!timeoutId) {
timeoutId = setTimeout(function() {
e.target.innerHTML = original.textContent;
original.innerHTML = e.target.innerHTML;
},1500);
}
}).on('mouseout', function(e){
if(timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" id="write">
<div class="tooltip">
<span id="original">test</span> <!--text to be written in text area-->
<span class="tooltiptext"> <!--holds words to be displayed on hover-->
<span id="hold" class="popUpWord">hello</span>
<br>
<span class="popUpWord">dog</span>
</span>
</div>
<div class="tooltip">
<span>test</span>
<span class="tooltiptext">
<span class="popUpWord">hello</span>
<br>
<span class="popUpWord">test</span>
</span>
</div>
</div>
You will need to store the new text strings in a variable. Otherwise you are just setting it right back:
timeoutId=window.setTimeout(function()
{
var child = e.currentTarget,
parent = e.fromElement.parentElement.parentElement.childNodes[0].childNodes[0],
childtext = child.innerText,
parenttext = parent.innerText
child.innerHTML = parenttext;
parent.innerHTML = childtext;
},1500);

Categories

Resources