modify function for local HTML code - javascript

I have function that works perfect, but not for my scope:
function _svgToCanvas() {
var nodesToRecover = [];
var nodesToRemove = [];
var svgElems = document.getElementsByTagName('svg');
for (var i = 0; i < svgElems.length; i++) {
var node = svgElems[i];
var parentNode = node.parentNode;
var svg = parentNode.innerHTML;
var canvas = document.createElement('canvas');
canvg(canvas, svg);
nodesToRecover.push({
parent: parentNode,
child: node
});
parentNode.removeChild(node);
nodesToRemove.push({
parent: parentNode,
child: canvas
});
parentNode.appendChild(canvas);
}
}
I'm trying to modify it for using local code that comes from param, like this:
function _svgToCanvas(content) {
var nodesToRecover = [];
var nodesToRemove = [];
var svgElems = content.getElementsByTagName('svg');
for (var i = 0; i < svgElems.length; i++) {
}
return content;
}
var content = $('#main_contents').get(0);
result = _svgToCanvas(content);
But I can't modify the for loop. How to modify it?

Looks like the "var svg = parentNode.innerHTML;" doesn't give you the correct parameter for function canvg.
This piece of code comes from canvg.js, try it.
function _svgToCanvas(content) {
var svgTags = content.querySelectorAll('svg');
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var c = document.createElement('canvas');
c.width = svgTag.clientWidth;
c.height = svgTag.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}
return content;
}
This funtion will not change the original content, and just return a new dom node.
function _svgToCanvas(content) {
var newContent = content.cloneNode(true);
var svgTags = newContent.querySelectorAll('svg');
var svgTagsOriginal = content.querySelectorAll('svg');
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var svgTagOriginal = svgTagsOriginal[i];
var c = document.createElement('canvas');
c.width = svgTagOriginal.clientWidth;
c.height = svgTagOriginal.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
content.appendChild(c);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}
return newContent;
}

Related

I just want to put some texts between tags using appendchild methods with Javascript

This code below is a javascript code to change texts and background properties from the body tag at the same time when the browser is clicked. I've just followed rules in w3school.com, actually, I'm doing the same as the examples do, but mine won't work and I've failed to find my fault. plz, help me.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
Here's your problem
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
Please note that the javascript functions that have plural names often return arrays which is the case here
document.getElementsByTagName("body") returns an array and you are trying to perform an invalid action, that is append child, to this array. You need to access an element using index and then perform this action.
so using
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv); should fix your problem.
Use document.getElementsByTagName("body")[0] to achieve expected result, as getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as a NodeList object.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
codepen - https://codepen.io/nagasai/pen/NLBXJE
Please refer this link for more details - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
I just change appendChild to document.body.appendChild(helloDiv) and added ID attribute for that div:
var helloDiv = document.createElement("div");
helloDiv.id = "myDIV";
document.body.appendChild(helloDiv);
var helloText = document.createTextNode("Click me");
helloDiv.appendChild(helloText);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
var helloText = document.getElementById("myDIV");
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[6]+complementary[1]+complementary[2]).toString(16);
var clnumber2 = (complementary[0]+complementary[2]+complementary[6]).toString(11);
body.style.backgroundColor = "#"+ number.toString();
helloText.style.color = "#"+number.toString();
}

Why is SetTimeout not executing?

I'm trying to write a javascript bookmark that, based on the current URL, navigates you to another page. Then after that navigation is done, it looks for a particular ID tag then navigates you again.
I have the first navigation done and working:
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
})();
however when I try to use a SetTimeout to delay the script so I can grab the ID i need from the page I navigated to, nothing happens (for now I just have a window alert in there as a placeholder until I get the SetTimeout to work):
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
setTimeout(function(){window.alert("yes");}, 2000);
})();
Any ideas what's going on? When using javascript in bookmarks is it not possible to do what I'm trying to do?

why will lines 56 and 67 not work? (.votess +=1;)

var imgs = ['bmw.jpg', 'bugatti.jpg', 'classic.jpg', 'concept.jpg', 'corvette.jpg', 'dino.jpg', 'lambo.jpg', 'mcclaren.jpg', 'p1.jpg', 'porsche.jpg', 'rally.jpg', 'audi.jpg'];
// var imgs_count = {'bmw.jpg': 0, 'bugatti.jpg': 0, 'classic.jpg': 0, 'concept.jpg': 0, 'corvette.jpg': 0, 'dino.jpg': 0, 'lambo.jpg': 0, 'mcclaren.jpg': 0, 'p1.jpg': 0, 'porsche.jpg': 0,'rally.jpg': 0, 'audi.jpg':0}
// for (var i in imgs_count) {
// imgs_count[i]
// }
var allCars = [];
var votes;
function Car(file) {
this.file = file;
this.votes = 0;
allCars.push(this);
}
var bmw = new Car('bmw.jpg');
var bugatti = new Car('bugatti.jpg');
var classic = new Car('classic.jpg');
var concept = new Car('concept.jpg');
var corvette = new Car('corvette.jpg');
var dino = new Car('dino.jpg');
var lambo = new Car('lambo.jpg');
var mcclaren = new Car('mcclaren.jpg');
var p1 = new Car('p1.jpg');
var porsche =new Car('porsche.jpg');
var rally = new Car('rally.jpg');
var audi = new Car('audi.jpg');
var idx1 = 0;
var idx2 = 0;
var path = 'cars/';
var done = false;
function getRandomImage() {
idx1 = Math.floor(Math.random()*imgs.length);
var img1 = imgs[idx1];
idx2 = idx1;
while (idx2 == idx1) {
idx2 = Math.floor(Math.random()*imgs.length);
}
img2 = imgs[idx2];
document.getElementById('choice1').setAttribute('src', path + img1);
document.getElementById('choice2').setAttribute('src', path + img2);
}
function setOnClicks(id) {
document.getElementById(id).addEventListener('click', function(event) {
var choice = event.target.id;
if (choice === 'choice1') {
console.log(allCars);
var img = document.getElementById(id).getAttribute('src');
var allCars = img.slice(5,img.length);
this.allCars[idx1].votes += 1;
console.log(idx1);
console.log(this.allCars[idx1].votes)
if ( allCars[idx1].votes=3) {
done = true;
}
}
if (choice === 'choice2') {
var img = document.getElementById(id).getAttribute('src');
var allCars = img.slice(5,img.length);
console.log(idx2);
console.log(this.allCars[idx2].votes);
this.allCars[idx2].votes += 1;
if (allCars[idx2].votes == 3) {
done = true;
}
}
if (!done)
getRandomImage();
});
}
getRandomImage();
setOnClicks('choice1');
setOnClicks('choice2')l
You're overwriting your global allCars with a local var declaration of the same name:
var allCars = img.slice(5,img.length);
you are creating a local variable allCars under click event, while this.allCars is point to the allCars variable under window object
var allCars = img.slice(5,img.length); // this is a local variable
this.allCars[idx1].votes += 1; // this is same as window.allCars
console.log(idx1);

Javascript array to point variable name with similar function

I'm want to shorten this function with array
document.mySchedule.breakfast.onchange = function() {
var id = document.mySchedule.breakfast.selectedIndex;
var val = document.mySchedule.breakfast[id].value;
strUser[0]=val;
}
document.mySchedule.lunch.onchange = function() {
var id = document.mySchedule.lunch.selectedIndex;
var val = document.mySchedule.lunch[id].value;
strUser[1]=val;
}
document.mySchedule.dinner.onchange = function() {
var id = document.mySchedule.dinner.selectedIndex;
var val = document.mySchedule.dinner[id].value;
strUser[2]=val;
}
I'm try this way but it didn't seem to be work.
var selectData = ["breakfast","lunch","dinner"]
for(i = 0; i < selectData.lenght; i++) {
document.mySchedule.selectData[i].onchange = function() {
var id = document.mySchedule.selectData[i].selectedIndex;
var val = document.mySchedule.selectData[i][id].value;
strUser[i]=val;
}
}
by the way this use to control selector.
Hope someone can help. thank you
Use:
var selectData = ["breakfast","lunch","dinner"]
for(i = 0; i < selectData.lenght; i++) {
var e = document.getElementById(selectData[i]);
e.onchange = function(){
strUser[i] = e.value;
};
}

jQuery multiple parent() calls

I have this for loop that gets the id and text of parents elements:
for (var i = 1; i < parents_num; i++)
{
var prev_parent_text = jQuery(id).parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').attr('id');
}
What I am trying to do is to increase the number of parent() by 2 in each loop:
For example,
for i = 1:
var prev_parent_text = jQuery(id).parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').attr('id');
for i = 2:
var prev_parent_text = jQuery(id).parent().parent().parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').parent('ul').parent('li').attr('id');
for i = 3:
var prev_parent_text = jQuery(id).parent().parent().parent().parent().parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').parent('ul').parent('li').parent('ul').parent('li').attr('id');
and so on..
I have used the eq() function unsuccesfully:
var num = (i*2) - 2
var prev_parent_text = jQuery(id).parent().eq(num).find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').eq(num).attr('id');
Thank you for any help
Keep a reference for each, and update the reference for each step:
var $id = jQuery(id);
var $li = jQuery(id);
for (var i = 1; i < parents_num; i++) {
$id = $id.parent().parent();
$li = $li.parent('ul').parent('li');
var prev_parent_text = $id.find('> .myclass').text();
var prev_parent_id = $li.attr('id');
}
You could add a custom jquery function for that, like this:
$.fn.nparent = function(n) {
var elem = $(this);
for (var i=0;i<n;i++) {
elem = elem.parent();
}
return elem;
}
And use it like:
var id = $('#element').nparents(4).attr('id');

Categories