excluding particular elements from onbeforeprint in javascript - javascript

I am more familiar with CSS coding than with Javascript, so when I was tasked to find a way to display Link URLS during print but not on-screen, I ran into a bit of trouble. Using CSS, I can manage what I want just fine, but thanks to Internet Explorer's quirkiness, I've had to find a javascript solution to my problem.
I was able to solve my dilemma with this code to make the link URLs display on print, and then disappear off the page when print preview was closed.
window.onbeforeprint = function(){
var links = document.getElementsByTagName("a");
for (var i=0; i< links.length; i++){
var theContent = links[i].getAttribute("href");
if (!theContent == ""){
links[i].newContent = " [" + theContent + "] ";
links[i].innerHTML = links[i].innerHTML + links[i].newContent;
}
}
}
window.onafterprint = function(){
var links = document.getElementsByTagName("a");
for (var i=0; i< links.length; i++){
var theContent = links[i].innerHTML;
if (!theContent == ""){
var theBracket = theContent.indexOf(links[i].newContent);
var newContent = theContent.substring(0, theBracket);
links[i].innerHTML = newContent;
}
}
}
However, now my problem becomes that ALL the page link URLs are printed. But, obviously, I don't need to print things like the internal navigation URLs; that just makes the finished product look messy. Is there a way to exclude certain sections of the page, like a UL-list with the ID of Navigation, from the onbeforeprint/onafterprint functions in javascript?

getElementsByTagName can be used as a method of any DOM node.
Thus:
var links = document.getElementById('showURLs').getElementsByTagName('a');
Using an ID on the parent
Simply replace the variable definition for links in your code with the above. Like so:
window.onbeforeprint = function(){
var links = document.getElementById('showURLs').getElementsByTagName('a');
for (var i=0; i< links.length; i++){
var theContent = links[i].getAttribute("href");
if (!theContent == ""){
links[i].newContent = " [" + theContent + "] ";
links[i].innerHTML = links[i].innerHTML + links[i].newContent;
}
}
}
window.onafterprint = function(){
var links = document.getElementById('showURLs').getElementsByTagName('a');
for (var i=0; i< links.length; i++){
var theContent = links[i].innerHTML;
if (!theContent == ""){
var theBracket = theContent.indexOf(links[i].newContent);
var newContent = theContent.substring(0, theBracket);
links[i].innerHTML = newContent;
}
}
}
Excluding children of a specific element
window.onbeforeprint = function(){
var links = document.getElementsByTagName("a");
var exclude = document.getElementById("navBar").getElementsByTagName("a");
for (var i=0; i< links.length; i++) {
if (!in_array(links[i], exclude)) {
var theContent = links[i].getAttribute("href");
if (!theContent == "") {
links[i].newContent = " [" + theContent + "] ";
links[i].innerHTML = links[i].innerHTML + links[i].newContent;
}
}
}
}
We get an array of all links on the page and one of links in the exclusion element (here with an ID of "navBar"). Then, when we are looping through the links on the page, we first check if they're in the exclusion array, and only if they're not we act!
For that conditional we use the bool in_array(needle, haystack) function, which returns true if the needle is found in the haystack (an array), false otherwise. This function is actually an adaptation of PHP's native function - see PHP manual.
function in_array(needle, haystack) {
for (i=0;i<haystack.length;i++) {
if (haystack[i] == needle) {
return true;
}
}
return false;
}
See this JSfiddle I created to test it. If you run print preview in your browser, you'll be able to see the links on the right!
Hope this helps :)

Related

URL parameters are reordered when using anchor links with Inheriting UTMS

I am using a javascript on my site, which always inherits the UTM parameters to the links on the site.
However, this is not working, when the links are anchor links to a section of the site and the link the visitor used to visit the page contains the "gclid" parameter from google.
For example:
A visitor uses this link to visit a site:
domain.com?utm_source=test&utm_medium=test&utm_campaign=test&gclid=12345
The button link on the site with the anchor link will look like the following:
domain.com&gclid=12345?utm_source=test&utm_medium=test&utm_campaign=test#anchor
For some reason the "&gclid" part changes its position.
I've tested it with a link without an anchor and in this case the "gclid" parameter doesn't get inherited and the link works.
Of course, the second domain isn't working anymore and leads to a 404 error.
Does someone have an idea what could be the cause for this?
This is the javascript I am using to inherit the UTMs:
(function() {
var utmInheritingDomain = "grundl-institut.de"
utmRegExp = /(\&|\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,
links = document.getElementsByTagName("a"),
utms = [
"utm_medium={{URL - utm_medium}}",
"utm_source={{URL - utm_source}}",
"utm_campaign={{URL - utm_campaign}}"
];
for (var index = 0; index < links.length; index += 1) {
var tempLink = links[index].href,
tempParts;
if (tempLink.indexOf(utmInheritingDomain) > 0) {
tempLink = tempLink.replace(utmRegExp, "");
tempParts = tempLink.split("#");
if (tempParts[0].indexOf("?") < 0) {
tempParts[0] += "?" + utms.join("&");
} else {
tempParts[0] += "&" + utms.join("&");
}
tempLink = tempParts.join("#");
}
links[index].href = tempLink;
}
}());
EDIT: It seems like the following script don`t causes this problem:
<script>
(function() {
var domainsToDecorate = [
'domain.com',
],
queryParams = [
'utm_medium',
'utm_source',
'utm_campaign',
]
var links = document.querySelectorAll('a');
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) {
if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
links[linkIndex].href = decorateUrl(links[linkIndex].href);
}
}
}
function decorateUrl(urlToDecorate) {
urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
var collectedQueryParams = [];
for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
if (getQueryParam(queryParams[queryIndex])) {
collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
}
}
return urlToDecorate + collectedQueryParams.join('&');
}
// borrowed from https://stackoverflow.com/questions/831030/
// a function that retrieves the value of a query parameter
function getQueryParam(name) {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search))
return decodeURIComponent(name[1]);
}
})();
</script>
You really should not change URLs with regexp and string manipulation.
Here is the recommended way
const url = new URL(location.href); // change to tempLink
utms = [
"utm_medium=med",
"utm_source=src",
"utm_campaign=camp"
];
utms.forEach(utm => url.searchParams.set(...utm.split("=")))
console.log(url.toString())

Ignoring ' from javascript code, SQLite

I have a french category named piqûres d'insectes that I am pulling from a SQLite database. Unfortunately, the ' in the category keeps breaking my javascript code, as seen in my pictures where it turns my breadcrumbs into undefined (half the word is missing as well clearly from the apostrophe). Is there a way I can pull this as just text so it does not break my code?
Javascript:
function txSuccessListAddSymptoms(tx,results) {
//console.log("Read Additional Symptoms success");
var category = getUrlVars().category;
var mainsymptom = getUrlVars().mainsymptom;
var len = results.rows.length;
var addSymp;
for (var i=0; i < len; i = i + 1) {
addSymp = results.rows.item(i);
};
$('#addSymps').listview('refresh');
}
You can use an escape character: \'
So for example try to use: piqûres d\'insectes
You can use the original name by adding this lines of code:
var str = getUrlVars().category;
var category = str.replace("'", "\'");
This code changes the ' to \' if it is in the name.
I hope this helped for you
EDIT::
Soo.. this would be your script:
function txSuccessListAddSymptoms(tx,results) {
//console.log("Read Additional Symptoms success");
var str = getUrlVars().category;
var category = str.replace("'", "\'");
var mainsymptom = getUrlVars().mainsymptom;
var len = results.rows.length;
var addSymp;
for (var i=0; i < len; i = i + 1) {
addSymp = results.rows.item(i);
};
$('#addSymps').listview('refresh');
}

how to the link number in a web page using javascript or jquery

How to get the index number of a link? on clicking on the link?
i have tried this code, to display the values
alert("i am script");
var an=[];
var href=[];
var atext=[]
an = document.getElementsByTagName("a");
for(var i=0;i<an.length;i++)
{
alert("i am inside for");
href[i]=an[i].getAttribute("href");
atext[i]=an[i].innerHTML;
}
With JavaScript way:
var links = document.getElementsByTagName('a');
for(var i = 0; i< links.length; i++){
alert('index is: '+i+' link is: '+links[i].href);
}
jQuery Way:
var links = $('a');
$.each(links, function(index, link){
alert('index is: '+index+' link is: '+$(link).attr('href'));
});
You said "on clicking on the link" right? Here you have:
$("a").click(function(){
var index = $(this).index();
alert(index);
});
Cheers
by javascript use document.links
var arr = [], l = document.links;
for(var i=0; i<l.length; i++) {
arr.push(l[i].href);
}
reference get all the href attributes of a web site
Update TO get the index no
$("a").click(function(e){
e.preventDefault();
$(document).find("a").each(function(index,val){
alert("it is " + index + " whose href is " +$(val).attr("href"));
});
});
Try this JavaScript:
Html:
<div id="xx">
link 1
link 2
link 3
link 4
</div>
javascript:
var g = document.getElementById('xx');
for (var i = 0, len = g.children.length; i < len; i++)
{
(function(index){
g.children[i].onclick = function(){
alert(index) ;
}
})(i);
}

Replace a space within a SPAN tag with a BR tag

I need to replace the space between the 2 words with a BR tag. I've tried quite a few things, this one I thought would work, but the original script only does it to the first item. :( I need it to replace it on all the menu items.
It's for menu text on a CMS, so I won't know what the text is going to be. All I know is that it will always be no more than 2 words.
I can use either JS or jQuery.
Demo here: JS Bin Link
HTML:
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
JavaScript:
// Doesnt work
// var span = document.getElementsByTagName(".navtext");
// Only works for the first one
var span = document.querySelector(".navtext");
// Doesnt work
// var span = document.querySelectorAll("navtext");
function space() {
var elem = document.createElement("br");
// elem.className = "space";
// elem.textContent = " ";
return elem;
}
function replace(elem) {
for(var i = 0; i < elem.childNodes.length; i++) {
var node = elem.childNodes[i];
if(node.nodeType === 1) {
replace(node);
} else {
var current = node;
var pos;
while(~(pos = current.nodeValue.indexOf(" "))) {
var next = current.splitText(pos + 1);
current.nodeValue = current.nodeValue.slice(0, -1);
current.parentNode.insertBefore(space(), next);
current = next;
i += 2;
}
}
}
}
replace(span);
I think, you dont want to use jQuery. Well, Here is quick solution:
var elms = document.querySelectorAll(".navtext");
for(var i=0; i<elms.length; i++){
elms[i].innerHTML = elms[i].innerHTML.replace(/\s/gi, "<br />");
}
Here is the jsfiddle: http://jsfiddle.net/ashishanexpert/NrTtg/
using jQuery you can do this:
$("span.navtext").each(function(){
$(this).html($(this).text().replace(/ /g,"<br />"));
})
If you install jQuery you can make it all more simple. Follow the installation instructions and then the code you'll need is something like:
jQuery(function($) {
// for each navtext run the described function
$(".navtext").each(function() {
// "this" represents the navtext
// replace all " " with "<br/>" from this's html
var code = $(this).text();
code = code.replace(" ", "<br/>");
// update this's html with the replacement
$(this).html(code);
});
});
Someone on twitter provided me with a fix, which was exactly like what Ashish answered.
var spans = document.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}
But that would quite work for me, but it did give me my answer! So thanks to Pete Williams
This is the code I went with:
var spans = document.querySelectorAll('.navtext');
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}

How to list childNodes names?

I have some sample website and I want to display the number of child nodes in the entire document and in the body node.
I manage to do it using code:
var childDoc = document.childNodes.length;
alert("Document have " + childDoc + " child nodes");
var childDoc2 = document.body.childNodes.length;
alert("Body have " + childDoc2 + " child nodes");
Now I need to list those nodes names but i dont know how. Can anyone help me?
EDIT.
working solution
var bodyChilds = document.body.childNodes;
var strg = "";
for(var i=0; i < bodyChilds.length; i++){
strg = strg + bodyChilds[i].nodeName + "\n";
}
alert (strg);
Just use simple loop and array index.
You can read more here : ChildNodes
for (var i=0;i<document.body.childNodes.length;i++)
{
//current node in childNodes[i]
}
To get the each childs (tag) name
var bodyChilds = document.body.childNodes;
var tagNames = [];
var localNames = [];
var nodeNames = [];
for(var i=0; i<bodyChilds.length; i++){
// note: tag name will be undefined when is a text node
//Here you can check null/undefined and take decision according to your need
tagNames.push(bodyChilds[i].tagName);
localNames.push(bodyChilds[i].localName) //Name provided by developer in html
nodeNames.push(bodyChilds[i].nodeName)
}
console.log(tagNames);
console.log(localNames);
console.log(nodeNames);

Categories

Resources