Create new div element from scratch on mouseovering a text with DOM - javascript

I'm trying to work on getting "a tooltip" on hovering a text.
This tooltip should be placed below the text. The tooltip should get its content from a database but I can handle that part, and styling it with css. Only problem here is that I can't create a new div element from scratch when mouseovering.
My current code uses existing div element but the code is supposed to create a new div element where place the code.
<script>
function createTooltip(str)
{
if (str == "" || !str)
{
return;
}
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "tooltip.php?s="+str, true);
xmlhttp.send();
}
function removeTooltip()
{
document.getElementById("txtHint").innerHTML = "";
}
</script>
<p><br>
Test
<br><br>
<div id="txtHint"></div></p>
The tooltip.php file has this content in it:
<?php
$q = intval($_GET['s']);
echo $q;
?>
For now it just prints the rel attribute in function. Now what I really want it to do is to create completely new div with the xml response in it, instead of an existing div. So this tooltip should appear below the text, like with this existing div. In future I will make it a hover div element, so it just hovers on all content.
Thank you for your time, I appreciate it.

You can use .hover() function to define both mouseover/mouseout events. You can use .after() to append new DIV and .remove() to remove it.
Assuming this is the element you hover over:
Test
This sample demonstrates the effect:
$('#test').hover(
function() {
var text = "Tooltip for rel: " + this.rel;
$(this).after($("<div></div>").html(text).addClass("tooltip"));
},
function() {
$(this).next().remove();
}
)
And here's live demo: http://jsfiddle.net/3LgWk/1/
Oh and jQuery makes AJAX calls a lot easier as well - give it a look when you get a chance.

Related

Uploading Images to WYSIWYG editor and having default styling applied

I have created a wysiwyg text editor for my site and am trying to work with images.
So far I've got my image being uploaded and being added to my text editor where I want it using something like this:
$("#upload_wysiwyg_image").unbind("click").bind("click", function() {
var formData = new FormData();
var image_to_upload = document.getElementById("wysiwyg_image").files[0];
formData.append("wysiwyg_image", image_to_upload);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText.includes('uploaded')){
var upload_string = this.responseText;
var image_name = upload_string.replace("uploaded ","")
var image_path = '../media/wysiwyg_images/'+image_name;
execCmdWithArg('insertImage', image_path);
}
}
};
xmlhttp.open("POST", "upload_wysiwyg_image.php", true);
xmlhttp.send(formData);
});
function execCmdWithArg (command, arg){
richTextField.document.execCommand(command, false, arg);
}
I want to be able to format the image at this point when it is being inserted. So for instance set a max-width/max-height or be able to select a float value for positioning.
Can this be done at this point while it is being inserted or will I need to insert it, and then call another function to set values for styling?
If anyone can point me in the right direction for this it would be greatly appreciated.

How to update innerHTML without modifying the entire content?

I have a javascript (AJAX) that periodically makes an XMLHttpRequest to get some data from a PHP file and append the returned data to the innerHTML of a <p> tag. However, every time the new content gets added to the block, the entire content of the paragraph seems to reload: when I select some text, the selection disappears when the data is updated.
Here's the code:
<script>
function requestChange(){
setInterval(updateData, 2000);
}
function updateData(){
var req = new XMLHttpRequest();
var url = "content_provider.php";
req.open("POST", url, true);
req.send();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
var data = req.responseText;
//updating the innerHTML content
document.getElementById('data').innerHTML += data;
}
};
}
</script>
<body onload="requestChange()">
<p id="data"></p>
</body>
How do I make the change in the innerHTML static?
You can try .insertAdjacentHTML()
It's what you need in this case because insertAdjacentHTML inserts the resulting nodes into the DOM tree at a specified position (first parameter), but does not reparse the hole tree.
document.getElementById('data').insertAdjacentHTML('beforeend', data);
Unfortunately using innerHTML will always destroy the previous content, if you are using jQuery you can instead use the append method, you haven't mentioned jQuery, so I'll assume that you're not using it.
You can instead use insertAdjacentHTML() instead of innerHTML, this method requires you to pass one of the positions below as the first argument and then the text you wish to add.
'beforebegin' // Before the element itself.
'afterbegin' // Just inside the element, before its first child.
'beforeend' //Just inside the element, after its last child.
'afterend' //After the element itself.
In your case here's how it would look:
document.getElementById('data').insertAdjacentHTML('beforeend', html_to_insert);
I didn't tested it but I think, this will work if you append a new container everytime you receive a new response:
function requestChange(){
setInterval(updateData, 2000);
}
function updateData(){
var req = new XMLHttpRequest();
var url = "content_provider.php";
req.open("POST", url, true);
req.send();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
var data = req.responseText;
var newInfoBox = document.createElement('SPAN');
newInfoBox.innerHTML = data;
//updating the innerHTML content
document.getElementById('data').appendChild(newInfoBox);
}
};
}
</script>
<body onload="requestChange()">
<p id="data"></p>
</body>

Create a loop for read a text file or real time changes

So, what I did it's to collect an information from a text file, and then transform that into text on the html page. Here's the code:
HTML:
<div id="text" class="text"></div>
JavaScript:
var text_print = new XMLHttpRequest();
text_print.open("GET", "file.txt", true);
text_print.onload = function (){
document.getElementById("text").innerHTML=text_print.responseText;
text_print.send(null);
What I need to do now, it's to make this script run every second.
The file.txt in my server changes constantly, so I need that the information printed on screen change when the file changes.
Thank you.
This is not the most efficient way to do it, but if you still decide to continue, this can help you.
window.setInterval(function(){
var text_print = new XMLHttpRequest();
text_print.open("GET", "http://localhost/post/file.txt", true);
text_print.send();
text_print.onreadystatechange = function () {
if (text_print.readyState == 4) {
if(text_print.status == 200) {
document.getElementById("text").innerHTML=text_print.responseText;
}
}
}
}, 1000);

Call javascripting and display result in right hand frame

I've a menu on the left side of a frame.
I'm trying to call a javascript that will load a new html in the right side of the frame generated from XML data and XSL template.
The code to do it in one page with fixed parameters works fine. The two issues I struggle with is:
How to make it flexible so I can use a different xml data and template on the call to the script
How to present the data in the right hand frame pane.
This is the code for the left hand pane:
<html>
<head>
<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}
function displayResult(xmlid,xslid)
{
xml = loadXMLDoc("XMLDATA/xmlid");
xsl = loadXMLDoc("XMLDATA/xslid");
// code for IE
if (window.ActiveXObject || xhttp.responseType == "msxml-document")
{
ex = xml.transformNode(xsl);
document.getElementById("example").innerHTML = ex;
}
// code for Chrome, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("example").appendChild(resultDocument);
}
}
</script>
</head>
<body>
<p>TEST</p>
<p>TEST</p>
<div id="example" />
</body>
</html>
If I omit the both arguments in the script call:
TEST
and assign the data sources in the parameters here:
xml = loadXMLDoc("XMLDATA/cdcatalog.xml");
xsl = loadXMLDoc("XMLDATA/cdcatalog.xsl");
Then it works on the same page.
I'm not a programmer so some help would be great.
You're not using the variables that you're passing in, you're simply using static text.
At the start of function displayResult(xmlid,xslid) change...
xml = loadXMLDoc("XMLDATA/xmlid");
xsl = loadXMLDoc("XMLDATA/xslid");
To...
xml = loadXMLDoc(xmlid);
xsl = loadXMLDoc(xslid);
Update - in response to the OPs comments...
If you want to move elements around the page, I would seriously consider looking at jquery which will easily allow you to detach the items and append them to another area.
For example...
$(function(){
var $rightArea = $("#rightarea");
$("#leftarea *").each(function(){
$(this).detach().appendTo($rightArea);
});
});

dynamically creating HTML divs with JS from XML

Im looking for a bit of Yoda like guidance on a project im working on. Im trying to dynamically generate div's in a web page based around XML data which is read in from a php server. Im punching a bit above my experience weight which is good for learning.
Was wondering if someone could point me in the right direction as far a tutorials or give me some guidance to see if im on the right track etc.
The XML im loading in is...
<item>
<id>1</id>
<name>Johnothan</name>
<message>hello world</message>
</item>
<item>
<id>2</id>
<name>Fredrico</name>
<message>hello world</message>
</item>...etc
My Ajax function to call.
function ajax(site, params){
var xmlhttp;
var i;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlDoc=xmlhttp.responseXML;
}
}
xmlhttp.open("POST", site, false);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(params);
}
JS Div generation
function information(){
xmlReturned = xmlDoc.getElementsByTagName("item");
for (i=0; i<xmlReturned.length; i++){
newDiv(i);
}
function newDiv(i){
var id = xmlReturned[i].getElementsByTagName("id")[0].firstChild.nodeValue;
var name = xmlReturned[i].getElementsByTagName("name")[0].firstChild.nodeValue;
var message = xmlReturned[i].getElementsByTagName("message" [0].firstChild.nodeValue;
//Now im trying to place the dynamic XML information within a table with in a new DIV in the HTML.
}
My HTML is pretty basic it calls the information() function with the body tag loads.
Am I looking in the right direction?? Can someone help me out or recommend a tutorial?
Thanks for your time
Try using jQuery. It simplifies the task that you are trying to do.
http://api.jquery.com/category/manipulation/
Eg.
var newDiv = $('<div/>').text(sampleText);
parentDiv.append(newDiv);
Useful example of using jquery to do your task:
http://think2loud.com/224-reading-xml-with-jquery/
i have this code in a jquery popup here is the code
jQuery(document).ready(function(){
var showmask = function() {
var dialogLeft = ((jQuery(window).width() - jQuery("#outerFbDialog").outerWidth()) / 2) + jQuery(window).scrollLeft() + "px";
var dialogTop = "100px";
/* uncomment this to place dialog in the center of window.
var dialogTop = ((jQuery(window).height() - jQuery("#outerFbDialog").outerHeight()) / 2) + jQuery(window).scrollTop() +"px";
*/
jQuery("#themask").css({'width':jQuery(window).width(),'height':jQuery(document).height()});
jQuery("#themask").fadeTo('slow',0.7);
jQuery("#outerFbDialog").css({'left': dialogLeft,'top':dialogTop});
jQuery("#outerFbDialog").show();
$('#themask').click(function () {
jQuery(this).hide();
jQuery("#outerFbDialog").hide();
});
}
// check for escape key
$(document).click(function(e) {
jQuery("#themask").hide();
jQuery("#outerFbDialog").hide();
});
showmask();
});

Categories

Resources