My URL Parameter forwarding script isn't working - javascript

My problem is simple, I have some links in my page and I want them to be updated according to the URL parameter the user used to enter the site, basically I want the URLs present in my HTML page to be updated dynamically
function getCookieValueByRegEx2(a, b) {
b = document.cookie.match("(^|;)\\s*" + a + "\\s*=\\s*([^;]+)");
return b ? b.pop() : "";
}
//BETFINAL
var PROMO_NEW_BETFINAL = $("#PROMO_NEW_BETFINAL").attr("href");
var replaced_PROMO_NEW_BETFINAL = PROMO_NEW_BETFINAL.replace(
"/1?cid=fbc_",
"/1?cid=fbc_" + getCookieValueByRegEx2("_fbc")
);
$("#PROMO_NEW_BETFINAL").attr("href", replaced_PROMO_NEW_BETFINAL);
$("#PROMO_NEW_BETFINAL").on("click", function() {
window.location = replaced_PROMO_NEW_BETFINAL;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<area
id="PROMO_NEW_BETFINAL"
target="_self"
alt="BetFinal"
title="BetFinal"
href="https://record.gotobetfinal.com/v2/text/60/56/d391859f-f32f-11ec-88a6-2eb982ce984b/1?cid=fbc_"
coords="0,1000,1080,3150"
shape="rect"
onclick="dataLayer.push({'event':'banner-click','eventCategory':'click','eventAction':'banner-click'});"
/>
For some reason the script isn't working

Related

Adding Hyperlinks to Images in a JavaScript Random Images Array

I have a random image generating array and I am hoping to insert hyperlinks associated with each image but I can't seem to find an answer or solution that works; or that I can understand enough to adapt to my situation/code. I am a javascript novice just trying to learn as much as I can as I go! Thanks in advance to any help, all is appreciated!
JS as follows:
var random_images_array = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
function getRandomImage(imgAr, path) {
path = path || 'img/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
HTML:
<div id="heroImage" style="text-align: center">
<script type="text/javascript">getRandomImage(random_images_array, 'img/heroImage/')</script>
</div>
Here's what I think you're trying to accomplish. Note: don't use document.write -- that has very specific uses and this isn't a good one. Rather use the innerHTML property (and there are other ways too). I modified the code so you could see the result in the snippet.
let random_images_array = [{
img: "https://picsum.photos/200/300?1",
link: "https://google.com"
},
{
img: "https://picsum.photos/200/300?2",
link: "https://yahoo.com"
},
{
img: "https://picsum.photos/200/300?3",
link: "https://loren.picsum.com"
}
];
function getRandomImage(imgAr, path) {
path = path || 'img/'; // default path here
path = ''; // JUST FOR S.O. TESTING
let num = Math.floor(Math.random() * imgAr.length);
let img = path + imgAr[num].img;
let imgStr = `<a href='${imgAr[num].link}'><img src="${img}" alt="" border="0" /></a>`;
document.querySelector('#heroImage').innerHTML = imgStr;
}
window.addEventListener('DOMContentLoaded', () => {
getRandomImage(random_images_array, 'img/heroImage/')
})
<div id="heroImage" style="text-align: center">
</div>
picsum answers GETs from picsum.photos/width/height by redirecting to a random image with the requested dimensions.
In order to have the image and the link match, you must make the picsum GET request and get the redirect URL from the response "Location" header. That's the URL that should be placed in the DOM.
After running the snippet, right-click the image and open it in new tab. Note the same image appears. Using the original GET url as the href will direct user to a new random image.
// super simple promise-returning http request
async function get(url) {
return new Promise(resolve => {
const xmlHttp = new XMLHttpRequest();
xmlHttp.addEventListener("load", () => resolve(xmlHttp));
xmlHttp.open("GET", url);
xmlHttp.send();
});
}
async function getRandomImage(width, height) {
const url = `https://picsum.photos/${width}/${height}`;
let res = await get(url);
// this is the important part: we need the redirect url for the image
const redirectURL = res.responseURL
const html = `<a href='${redirectURL}' target='_blank'><img src="${redirectURL}" alt=""/></a>`;
const el = document.querySelector('#heroImage')
el.innerHTML = html;
}
getRandomImage(200, 300)
<div id="heroImage" style="text-align: center">
</div>
Notice that we don't need to fool around with a random pick from an array of URLs. picsum does the randomizing on the initial GET.

Merge duplicate URLs into 1 URL, Javascript

I have function, which shows / outputs the urls from the textarea. At the moment however it won't merge duplicates into 1 URL. How can I output same urls as one (Merge http://google.com, www.google.com, http://www.google.com, or just google.com)?
At the moment:
Should be:
My Code:
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/[^\s]+)/g;
$("#textarea").val().replace(urlRegex, function(url) {
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea"></textarea>
<div id="converted_url"></div>
JS FIDDLE
Credits
Scott Marcus, Stackoverflow
Simple fix: store matched urls in array and append link only if url is not present in that array.
UPDATE: changed regex to /((https?:\/\/|www\.|\/\/)[^\s]+)/g so it matches links starting with http://, https://, www., //. You may use any other regex covering other cases (like http://www.) just modify stored url so that you'll be able to compare it (you may want to treat http and https link as unique).
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /((https?:\/\/|www\.|\/\/)[^\s]+)/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
let trimmedUrl = url.replace(/^(https?:\/\/|www\.|\/\/)/, "");
if (found.includes(trimmedUrl)) {
return;
}
found.push(trimmedUrl);
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
var link = "";
var protOmmitedURL = url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
if (found.includes(protOmmitedURL)) {
return;
}else
{
link = '<div>' + url + '</div>';
found.push(protOmmitedURL);
}
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>

How do I change an image with javascript without an onclick event?

I'm trying to get a dummy username and profile picture to display at random, at a random interval. I also want the usernames to match their respective profile pictures.
I currently I have html that displays the usernames correctly
<p id="usr"></p>
<img id="changeimage" src="" alt="Profile picture">
And javascript like this
var players = ['player1', 'player2', 'player3']
var playerpics = ['player1.jpg', 'player2.jpg', 'player3.jpg'];
var activeuser;
var playerpicker = function (activeuser) {
usr.innerHTML = players[activeuser];
changeimage.innerHTML = "<img src='" + playerpics[activeuser] + "' />";
};
setInterval(function () {
var oneintwelve = Math.floor(Math.random() * 12);
if (oneintwelve === 3) {
activeuser = Math.floor(Math.random() * 3);
playerpicker(activeuser);
};
}, 1000);
I know I'm doing something wrong with implementing the new IMG tag, forgive me if I'm not doing this the best way, I'm fairly new to this. Thanks for the help.
You're almost there, you can change the src attribute of an image. Also you didn't quite correctly selected the elements.
var playerpicker = function (activeuser) {
document.getElementById("usr").innerHTML = players[activeuser];
document.getElementById("changeimage").src= playerpics[activeuser];
};
Check this link, it will help you learn http://www.w3schools.com/jsref/dom_obj_select.asp

Display random image with fitting link

I'm using the below code to show random images which works fine. How can I add to this code so that each image gets it's own link? I.e. if "knife.png" is randomly picked I want it to have a link that takes the user to "products/knife.html" and so on.
Thanks for any help!
<div id="box">
<img id="image" /></div>
<script type='text/javascript'>
var images = [
"images/knife.png",
"images/fork.png",
"images/spoon.png",
"images/chopsticks.png",];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
randImg();
Generalize your list of images so that that it can be multi-purposed - you can add additional information later. Then surround the image by an anchor tag (<a>) and use the following.
<div id="box">
<a name="imagelink"><img id="image" /></a>
</div>
<script type='text/javascript'>
var images = ["knife","fork","spoon","chopsticks",];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = "images/"+images[x]+".png";
document.getElementById('imagelink').href="products/"+images[x]+".html";
}
</script>
randImg();
Try doing something like this example. Like all these other guys have said, it's better to store this info in a database or something, but to answer your question, put the values you need into an object in the array and reference the properties of the object instead of just having a string array.
<div id="box">
<a id="a"><img id="image" /></a>
</div>
<script type='text/javascript'>
var images =
[
imageUrlPair = { ImgSrc:"http://www.dansdata.com/images/bigknife/bigknife1280.jpg", Href:"http://reluctantgourmet.com/tools/cutlery/item/267-chefs-knife-choosing-the-right-cutlery" },
imageUrlPair = { ImgSrc:"http://www.hometownsevier.com/wp-content/uploads/2011/01/fork.jpg", Href:"http://eofdreams.com/fork.html" },
imageUrlPair = { ImgSrc:"http://upload.wikimedia.org/wikipedia/commons/9/92/Soup_Spoon.jpg", Href:"http://commons.wikimedia.org/wiki/File:Soup_Spoon.jpg" },
imageUrlPair = { ImgSrc:"http://upload.wikimedia.org/wikipedia/commons/6/61/Ouashi.jpg", Href:"http://commons.wikimedia.org/wiki/Chopsticks" },
]
function randImg() {
var size = images.length;
var x = Math.floor(size * Math.random());
var randomItem = images[x];
document.getElementById('image').src = randomItem.ImgSrc;
document.getElementById('a').href = randomItem.Href;
}
randImg();
</script>
Surround the img with an a
<img id="image" />
Then add
document.getElementById("link").href = images[x].replace(".png",".html");
The .replace is a bit crude, but you get the idea.
You can use a convention based approach. In this case the convention is that each product, will have an associated image at "/image/[product]/.png" and a page at "products/[product].html"
<div id="box">
<a id="link"><img id="image" /></a></div>
<script type='text/javascript'>
var products = [
"knife",
"fork",
"spoon",
"chopsticks",];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = "/images/" + products[x] + ".png";
document.getElementById('link').setAttribute("href", "products/" + products[x] + ".html");
}
randImg();
this is a very naive approach that won't scale very well. for example, if you have a list of products that changes frequently, or, you need to keep track of the number of available units. a more robust approach would be to store information about your products in a database, and a page that displays the data about a given product (a product detail page), and then use a data access technology to fetch a list of products for display in a product list page (similar to what you have here, except the list of products isn't hardcoded) and then each product would link to the product detail page.

regex/jquery to find domain(url) in div and append parameter

Previous stackoverflow
This jquery statement will look for domain.com and append ?parameter to the end of the URL. It will NOT append if ?parameter has already been added.
The problem: My current jquery modifies all URLs and not domain.com. Here is the regex statement that i would like to use and is tested to work. However, when implemented, nothing is appended. Any help is greatly appreciated!
Regex i would like to use:
\b(https?://)?([a-z0-9-]+\.)*domain\.com(/[^\s]*)?
RegexFiddle
JSFiddle for convience
Code to be modified
<div id="wp-content-editor-container" class="wp-editor-container"><textarea class="wp-editor-area" rows="10" tabindex="1" cols="40" name="content" id="content"><a title="Link to test domain" href="http://www.domain.com">Link to google</a>
<a href="http://www.google.com/directory/subdirectory/index.html">This is another link</a>
<a href="http://domain.com/directory/index.html">This is a 3rd link</a>
<a href="http://www.domain.com/subdir?parameter">this url already has parameters</a></textarea></div>
current jquery statement
var url = 'www.domain.com';
var append = '?parameter';
$(".wp-editor-area").each(function() {
$(this).text(urlify($(this).text()));
});
function urlify(text) {
var urlRegex = /(\b(https?|ftp|file):\/\/[www.domain.com][-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(urlRegex, function(url) {
// if the url does not contain append, concat append to the URL
if (url.indexOf(append) == -1) {
return url + append;
}
return url;
});
}
Current output
<a title="Link to test domain" href="http://www.domain.com?parameter">Link to google</a>
This is another link
This is a 3rd link
Test this code - it should be what you need (or at least starting point) >>
function urlify(text) {
var append = '?parameter';
text = text.replace(/("(?:(?:https?|ftp|file):\/\/)?(?:www.|)domain.com(?:\/[-a-z\d_.]+)*)(\?[^"]*|)(")/ig,
function(m, m1, m2, m3) {
return ((m1.length != 0) && (m2.length == 0)) ? m1 + append + m3 : m;
});
return text;
}
$(".wp-editor-area").each(function() {
this.innerHTML = urlify(this.innerHTML);
});

Categories

Resources