I am trying to direct after user click on "Finish" on a sharepoint survey. But the following code executes when user click on "Respond to this survey". Any idea what is happening.
<script type="text/javascript">
function redirect()
{
var inputcCtrls = document.getElementsByTagName("input");
for(var m=0; m<inputcCtrls.length; m++)
if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";
}
redirect();
</script>
I don't know about javascript, but in c# the code block
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";
would need to be in parenthesis as the if statement only applies to the next line of code, so the following would work
if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
{
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";
}
Edit thanks to graham's answer.
Change:
for(var m=0; m<inputcCtrls.length; m++)
if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish')
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = window.location = "http://www.google.com/";
to
for(var m=0; m<inputcCtrls.length; m++) {
if(inputcCtrls[m].type=='button'&&inputcCtrls[m].value=='Finish') {
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = function () { window.location = "http://www.google.com/" };
}
}
onclick wants a function. This is why I always use parathesis no matter if it's one line or not.
It's easier to assign a unique class name to the button and use document.getElementsByClassName than it is to loop through all the inputs to get the right one.
var inputcCtrls = document.getElementsByClassName("finalButton");
inputcCtrls[0].onclick = function() {
window.location = "http://www.google.com/";
}
Related
We do have some Campaigns (Google, facebook,...) When the user arrives the landingpage (abo.mysite.com) he does have the utm parameter utm_source=theCampaignSource. When the user clicks an CTA the CTA gives an new UTM utm_source=abo and he goes to shop.mysite.com.
We are not able to remove the UTM from abo.mysite.com.
Is there a way to check if a user have already an UTM, and when he does have one to kepp them until shop.mysite.com? So we know that the user is comming from Google (...)?
We know that how this Thing is set up is a very bad practice, and we are working on it.
Ive found a code snippet which is manipulating the links on a site:
links.forEach(function(link){
link.setAttribute("href","abo.mysite.com")
})
but i couldn get it work - cause i do have a lack of experience.
Update
To my specific needs a made it that way:
1) Remove existing UTM from Links on the Site
<script>
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
2) Hash the UTM in the URL
<script>
if(!window.jQuery) {
document.write('<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">\x3C/script>');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var parameters = getUrlVars();
var utm_source = decodeURIComponent(parameters['utm_source']);
var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
var utm_medium = decodeURIComponent(parameters['utm_medium']);
</script>
3)rewrite every URL on the Site with the hashed UTMs
<script>
$('a').each(function(){
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);
});
});
Edit
Thanks to Michele Pisani
this works well - BUT, if a user does not have an UTM, and he clicks the button, the UTM will be set to undefined
Is there a way to set the UTM Parameter from the URL when the User already has one, or to use the existing UTM (which are hardcoded in the button) when he does not have an UTM in the URL.
Edit 2 & update
Finally - with the help of you guys - i found a solution:
<script>
var link = document.querySelectorAll('a:not([href*="#"])');
for (var i = 0; i < link.length; i++) {
//link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
//var parameters = getUrlVars();
//var utm_source = decodeURIComponent(parameters['utm_source']);
//var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
//var utm_medium = decodeURIComponent(parameters['utm_medium']);
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
//var c = url.searchParams.get("c");
var utm_source = url.searchParams.get("utm_source");
var utm_campaign = url.searchParams.get("utm_campaign");
var utm_medium = url.searchParams.get("utm_medium");
$('a:not([href^="#"])').each(function() {
if(utm_source != "" && utm_source != null){
var href = $(this).attr("href");
href = href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
$(this).attr("href",href);
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign=' + utm_campaign + '&utm_medium=' + utm_medium);
}
});
});
</script>
With JavaScript, to remove UTM parameters from links in page you can try this function with regex:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
If you are using Google Tag Manager you can add it in a custom HTML tag and fires it on DOM Ready.
If you want to keep the fragment in the URL you can modify the function in this way:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
arr_link = (link[i].href).split("#");
var fragment = "";
if (arr_link[1]) { fragment = "#" + arr_link[1]; }
var my_new_url = arr_link[0].replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
link[i].href = my_new_url + fragment;
}
const ourUTMs = new URL(location.href).searchParams;
document.body.onclick = (e) => {
if (!isParamsContainsUTM(ourUTMs) || e.target.tagName !== "A") {
return;
}
try {
// Is valid url?, else we go to catch =)
const url = new URL(e.target.href);
e.preventDefault();
// Remove all utm params from link;
Array.from(url.searchParams).forEach(([k]) => {
if (k.startsWith("utm_")) {
url.searchParams.delete(k);
}
});
// Add our utm_ params to link
Array.from(ourUTMs).forEach(([k, v]) => {
url.searchParams.append(k, v);
});
// Open URL
window.open(url.toString());
} catch (e) {}
};
const isParamsContainsUTM = (arr = new URLSearchParams()) =>
Array.from(arr).some(([key]) => key.startsWith("utm_"));
I use ImgLikeOpera and Squid Caching Proxy to manage my bandwidth while on dialup. But, I can't set it to load one image at a time, so I had the bright idea to write a script that will open each image on a page one at a time in a new tab and then close them so that they'll be saved in my cache.
Script works great, added a start button so that I could control when it started... but can't figure out how to make a stop button that will interrupt the process. I tried a bunch of stuff and nothing works...
It seems like when it's in the loop it can't hear what's going on outside the loop...
I have a feeling that there is a very simple way to do this, but I'm getting frustrated. Isn't this what break or return is supposed to be for?
Here's the relevant parts of my script:
var box = document.createElement ('div');
box.id = 'mySelectBox';
document.body.appendChild (box);
box.innerHTML = 'click>';
var searchButton = document.createElement ('div');
searchButton.className = 'mySearchButton';
searchButton.textContent = 'Search and open';
box.insertBefore (searchButton, box.nextSibling);
var stopButton = document.createElement ('div');
stopButton.className = 'myStopButton';
stopButton.textContent = 'Stop';
box.insertBefore (stopButton, box.nextSibling);
var mytable = document.getElementById ('lair-sort-pets').getElementsByTagName ('img');
var linksToOpen = [];
var mywin2 = null;
function openpics () {
for (var J = 0, L = mytable.length; J < L; J++) {
linksToOpen.push (mytable[J].src); //-- Add URL to list
}
openLinksInSequence ();
};
function openLinksInSequence () {
if (mywin2) {
mywin2.close ();
mywin2 = null;
}
if (linksToOpen.length) {
var link = linksToOpen.shift ();
mywin2 = window.open (link, "my_win2");
mywin2.addEventListener ('load', openLinksInSequence, false);
}
}
searchButton.addEventListener ('click', openpics, true);
//stopButton.addEventListener ('click', , true);
How do I make the stop button actually stop any more links from loading?
Use a global state variable. Like so:
var okayToOpenLinks = true;
searchButton.addEventListener ('click', openpics);
stopButton.addEventListener ('click', stopLinkSequence);
function openpics () {
okayToOpenLinks = true;
if (linksToOpen.length === 0) {
for (var J = 0, L = mytable.length; J < L; J++) {
linksToOpen.push (mytable[J].src); //-- Add URL to list
}
}
openLinksInSequence ();
};
function stopLinkSequence () {
okayToOpenLinks = false;
}
function openLinksInSequence () {
if (mywin2) {
mywin2.close ();
mywin2 = null;
}
if (okayToOpenLinks && linksToOpen.length) {
var link = linksToOpen.shift ();
mywin2 = window.open (link, "my_win2");
mywin2.addEventListener ('load', openLinksInSequence, false);
}
}
I am trying to write a click event for an anchor tag in my tampermonkey script.
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);
for(var i=0; i<20; i++) {
if(i!==15)
contentTag.innerHTML+=(lines[i]+"<br>");
else {
contentTag.innerHTML+=("<a id=link1>Click me</a>");
var link = document.getElementById('link1');
link.addEventListener("click", function() {
window.alert('I am clicked');
}, false);
}
}
The alert message never gets triggered when I click on the link in the page dispalyed, even though I have a a click event listener defined. What am I doing wrong here?
It's the way you're adding HTML, you're reappending the link when you do this in the next iteration.
link.innerHTML += something
So the event handler is lost, and you can actually prove that by adding the event handler to the last element instead.
If you do it the proper way, creating elements and appending them, it works fine
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
for (var i = 0; i < 20; i++) {
if (i !== 15) {
var txt = document.createTextNode(lines[i] || ''),
br = document.createElement('br');
contentTag.appendChild(txt);
contentTag.appendChild(br);
} else {
var link = document.createElement('a');
link.id = 'link1';
link.innerHTML = 'Click me';
link.addEventListener("click", function () {
alert('clicked')
}, false);
contentTag.appendChild(link)
}
}
FIDDLE
Shoud be contentTag.innerHTML+=("<a id='link1'>Click me</a>");
Try this:
<script>
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);
for(var i=0; i<20; i++) {
if(i!==15)
contentTag.innerHTML+=(lines[i]+"<br>");
else {
contentTag.innerHTML+=("<a id=link"+i+">Click me</a>");
var link = document.getElementById('link'+i);
var att=document.createAttribute('onclick');
att.value="alert('Clicked !')";
link.setAttributeNode(att);
}
}
</script>
Demo: http://jsfiddle.net/TmJ38/
I have some simple functions in javascript which work fine in most browser except IE9. I have heard Ie9 is fussy about commas etc. But I cannot spot any obvious problems. Can anyone of you guys and gals shed any light? Full code below
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", load, false);
function load() {
//dom loaded
var elUserId = document.getElementById("user_id");
var elPasswordId = document.getElementById("password");
var elLoginMsg = document.getElementById("usernameMsg");
var elPasswordMsg = document.getElementById("passwordMsg");
var elIncreaseFontSize = document.getElementById("increaseFont");
var elResetFontSize = document.getElementById("resetFont");
var elChangeContrast = document.getElementById("changeContrast");
var elResetContrast = document.getElementById("resetContrast");
var logInbox = document.getElementById("loginBox");
var helpWithBB = document.getElementById("helpWithBB");
var fontUp = '135%';
var fontReset = '100%';
var black = '#000000';
var white = '#ffffff';
var divReset ='415px';
var divChange ='525px';
var txtSizeChange ='40.5em';
var txtReset ='42em';
elLoginMsg.style.display ='none';
elPasswordMsg.style.display = 'none';
elPasswordId.addEventListener("focus", function(){
showText(elPasswordMsg);
}, false);
elUserId.addEventListener("click", function(){
showText(elLoginMsg);
}, false);
elResetFontSize.addEventListener("click", function(){
//pass size change and element affected to be manipulated
//resetTextSize(fontReset,logInbox,elPasswordMsg);
changeTextSize(fontReset,logInbox,elPasswordMsg,divReset,txtReset);
});
elChangeContrast.addEventListener("click", function(){
//pass size change and element affected to be manipulated
changeContrast(logInbox, helpWithBB, black, white);
});
elResetContrast.addEventListener("click", function(){
document.location.reload(true);
});
elIncreaseFontSize.addEventListener("click", function(){
//pass size change and element affected to be manipulated
changeTextSize(fontUp,logInbox,elPasswordMsg,divChange,txtSizeChange);
});
function changeContrast(mainDiv, secDiv, txtColor, bkColor){
secDiv.style.background = bkColor;
mainDiv.style.background = bkColor;
showText(elPasswordMsg);
showText(elLoginMsg);
elLoginMsg.style.color = txtColor;
elPasswordMsg.style.color = txtColor;
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
anchors[i].style.color = txtColor;
}
var para = document.getElementsByTagName('p');
for(var i = 0; i < anchors.length; i++) {
para[i].style.color = txtColor;
}
}
function changeTextSize(fontUp, elDiv, msg, divH, msgT){
document.body.style.fontSize=fontUp;
elDiv.style.height = divH;
msg.style.top = msgT;
}
function showText(id){
id.style.display ='block';
}
}
</script>
You're missing the third parameter (useCapture) in some of your calls to addEventListener() but other than that nothing is obviously wrong. I know that Firefox has only started supporting addEventListener() without a third parameter within the last year, so it's possible IE 9 doesn't support it.
Update
So much for that theory. Two parameters seems fine in IE 9: http://jsfiddle.net/xZRy7/
I am developing an extension for Mozilla Firefox. A main function is to get the URL that the user is visiting and process it later. I tried the following Javascript code:
window.onload = function(){
alert(document.referrer);
}
That didnt work so I tried to inject an onclick event to every link using this:
window.onload = function(){
var links = document.links;
for(var i=0;i<links.length;++i){
links[i].onclick = show_href();
}
}
function show_href(){
alert(this.href);
}
But that also doesnt work. Any other approach?
Try this:
linktextx
linktexty
linktextz
<script>
window.onload = function() {
var links = document.links;
for(var i=0;i<links.length;i++){
links[i].onclick = function(){alert(this.href)};
}
}
</script>
See: http://jsfiddle.net/uXmWj/ for working demo
In the second approach, the problem could be the for loop.
window.onload = function(){
var links = document.links,
max,
i;
for(var i=0, max = links.length; i < max; i += 1) {
(function() {
var link = links[i];
link.onclick = function() {
alert(this.href);
}
})();
}
};
var anchors = document.getElementsByTagName('a');
for(var i=0,l=anchors.length;i<l;i++)
if(anchors[i].hasAttribute('href'))
anchors[i].onclick = function(){
alert(anchors[i].getAttribute('href'));
}