How can I change the pathname of a image in JavaScript? - javascript

searchURL: function() {
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var link, url, parser, newPathName = '',
emailUrl = /\/img\//,
newstr = '',
doc = document,
container,
container_id,
container_links,
container_images,
documentTableWrapper,
docBodyFirstChild,
nodeToTargetToInsertLP;
if (!doc.getElementById('container')) {
container = doc.createElement('div');
container.setAttribute('id', 'container');
container.className = 'container-avon-representative-news';
container_links = container.getElementsByTagName('a');
container_id = doc.getElementById('container');
docBodyFirstChild = doc.body.firstChild;
nodeToTargetToInsertLP = doc.getElementsByClassName('flexTile')[4];
if (nodeToTargetToInsertLP) {
documentTableWrapper = doc.getElementsByClassName('marginfix')[0];
container.appendChild(documentTableWrapper);
insertAfter(container, nodeToTargetToInsertLP);
} else {
documentTableWrapper = doc.getElementsByTagName('table')[0];
container.appendChild(documentTableWrapper);
doc.body.insertBefore(container, docBodyFirstChild);
}
} else {
container_links = doc.getElementById('container').getElementsByTagName('a');
}
container_images = container.getElementsByTagName('img');
for (var i = 0; i < container_images.length; i++) {
if (arguments[0] == "smo" || arguments[1] == "smodev") {
container_images[i].src = container_images[i].src.replace(emailUrl, '/images/dir_a/');
} else {
container_images[i].src = container_images[i].src.replace(emailUrl, '/static/images/dir_b/');
}
}
for (var i = 0, len = arguments.length; i < len; i++) {
url = getURL(arguments[i]);
for (var j = 0, jlen = container_links.length; j < jlen; j++) {
link = container_links[j];
if (link.href.indexOf(url) !== -1) {
parser = document.createElement('a');
parser.href = link.href;
link.setAttribute('target', '_self');
newPathName = parser.pathname;
if (newPathName.search(/Executive|District|Division|National/) != -1) {
newPathName = newPathName.split('/').pop();
newstr = newPathName;
} else {
newstr = newPathName;
}
link.href = newstr;
} else {
link.setAttribute('target', '_blank');
}
}
}
},
I have a loop which is going through the images which are children of a div:
var container_images = container.getElementsByTagName('img'),
emailUrl = /\/img\//;
for (var i = 0; i < container_images.length; i++) {
if (arguments[0] == "smo" || arguments[1] == "smodev") {
container_images[i].src = container_images[i].src.replace(emailUrl, '/images/dir_a/');
} else {
container_images[i].src = container_images[i].src.replace(emailUrl, '/static/images/dir_b/');
}
}
Strangely, this is working in one instance (another area of the server), but in another instance it's adding other pathnames/directories which I didn't even indicate?!
I figured replace is explicit enough:
xxx.src.replace(emailUrl, '/images/dir_a/');
If this image tag has its source attribute set to /\/img\// replace it with /images/dir_a/
Does anyone know a method which is more explicit and won't add directories which I didn't assign?
And could anyone explain how this is happening with the replace method?
UPDATE
To give some background the environment where I am not having any problems is as follows: My company uses a CMS to serve these pages. The file extension is called .page; I have never heard of that extension outside the use of the CMS so I supposed it's proprietary to the CMS.
Anyway, in the CMS you can also server html files like you would from any other server. But in this instance, when I check the source in dev tools, it seems to add <img src="http://xxx.xxx.com/REPSuite/static/html/inews_archives/static/images/dir_b/xxx.png"> instead of <img src="http://xxx.xxx.com/REPSuite/static/images/dir_b/xxx.png">

The issue is you are using .src and you want to be using .getAttribute('src') and .setAttribute('src', 'your new src').
HTMLImageElement.src
Is a DOMString that reflects the src HTML
attribute, containing the full URL of the image including base URI.
so when you call .src it gives you the full absolute current uri. You just want to get/set the src attribute. working example jsbin

The answer turned out to be so simple (of course after the fact). Anyway—because I was getting that funky path only in the other environment where the page was getting served, I simply made a conditional which checked for that funky path.
So instead of checking one regex I checked for two.
var emailUrl = /img\//gi,
tsUrl = /\/REPSuite\/static\/html\/inews_archives\/img\//gi;
for (var i = 0; i < avon_rep_container_images.length; i++) {
if (arguments[0] == "smo" || arguments[1] == "smodev") { // Checks what environment the page will be used in so we can change the src attribute of all the images in the document to the appropriate path
avon_rep_container_images[i].src = avon_rep_container_images[i].src.replace(emailUrl, '/images/avon_manager_news/');
} else if(!nodeToTargetToInsertLP) {
avon_rep_container_images[i].src = avon_rep_container_images[i].src.replace(tsUrl, '/REPSuite/static/images/rep_news/');
} else {
avon_rep_container_images[i].src = avon_rep_container_images[i].src.replace(emailUrl, '/static/images/rep_news/');
}
}
Thanks to everyone who helped out, I appreciate it!

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())

Recursive function can't check if generated index of a site (desc, title, img, etc stored in my database) is already on page

var infiniteResponseAAA= {
Poodwaddle_com: '"Poodwaddle.com", infiniteResponse[1].children[language].children[17].innerHTML, "Images\poodwaddle.com.jpg", searchBResponse[1].children[17].textContent',
SystemRequirementsLab_com: '"System Requirements Lab.com", infiniteResponse[1].children[language].children[18].innerHTML, "Images\systemrequirementslab.com.jpg", searchBResponse[1].children[18].textContent',
BrowsePad: '"BrowsePad.org", infiniteResponse[1].children[language].children[19].innerHTML, "Images\BrowsePad.org.jpg", searchBResponse[1].children[19].textContent',
SMMRY_com: '"SMMRY.com", infiniteResponse[1].children[language].children[20].innerHTML, "Images\smmry.com.jpg", searchBResponse[1].children[20].textContent',
Whatthefuckshouldimakefordinner_com: '"Whatthefuckshouldimakefordinner.com", infiniteResponse[1].children[language].children[21].innerHTML, "Images\Whatthefuckshouldimakefordinner.com.jpg", searchBResponse[1].children[21].textContent',
Coolors_co: '"Coolors.co", infiniteResponse[1].children[language].children[22].innerHTML, "Images\Coolors.co.jpg", searchBResponse[1].children[22].textContent',
Numbeo_com: '"Numbeo.com", infiniteResponse[1].children[language].children[23].innerHTML, "Images\Numbeo.com.jpg", searchBResponse[1].children[23].textContent',
Doesthedogdie_com: '"Doesthedogdie.com", infiniteResponse[1].children[language].children[24].innerHTML, "Images\Doesthedogdie.com.jpg", searchBResponse[1].children[24].textContent',
Online_Convert_com: '"Online-Convert.com", infiniteResponse[1].children[language].children[25].innerHTML, "Images\Online-Convert.com.jpg", searchBResponse[1].children[25].textContent'
}
var infiniteResponse= Object.keys(infiniteResponseAAA).sort();
var sitesOnPage = [];
var brLength= document.querySelectorAll("br").length;
var whereToAddIt= document.querySelectorAll("br")[brLength-1];
var observer = new IntersectionObserver(function(entries){
entries.forEach(function(entry) {
if (entry.isIntersecting) {
getDataInfiniteS();
}
});
});
observer.observe(whereToAddIt);
// Data checker
function getDataInfiniteS() {
InfiniteScrolling();
}
// Actual script
function InfiniteScrolling() {
var code;
// It gets the first 5 sites that are already on the page and puts them inside sitesOnPage
if (sitesOnPage[0] === undefined) {
var h2s= document.querySelectorAll("h2");
infiniteResponseAAA[infiniteResponse[0]].split(",")[0].replace(/["]/g, "");
for (var i=0; i < h2s.length; i++) {
if (h2s[i].innerHTML === infiniteResponseAAA[infiniteResponse[i]].split(",")[0].replace(/["]/g, "")) sitesOnPage.push(i);
}
}
function randomSiteInfosF(siteN) {
// Checks if it's a number and not a string or something else
if (typeof siteN !== "number") return;
siteChecker_RNG(siteN)
// Infos about the site: title
eval(`siteInfo${siteN}= infiniteResponseAAA[infiniteResponse[${eval(`randomSite${siteN}`)}]].split(",")`);
eval(`siteTitle${siteN}= siteInfo${siteN}[0].replace(/["]/g, "")`);
}
function siteChecker_RNG(siteN) {
var sitesAvailable= infiniteResponse.length;
var h2s= document.querySelectorAll("h2");
var randomSiteN= Math.floor(Math.random() * sitesAvailable);
// Return if all sites are loaded
if (h2s.length === sitesAvailable) return;
// Checks if the random number is a correct one
for (var i= 0; i < sitesOnPage.length; i++) {
if (randomSiteN === sitesOnPage[i]) {
siteChecker_RNG(siteN)
} else continue;
}
eval(`randomSite${siteN}= randomSiteN`);
}
var howManySitesPerLoad= 3;
for (let i= 0; i < howManySitesPerLoad; i++) {
randomSiteInfosF(i);
}
// Creates a new div for the sites loaded from the database
if (document.getElementById("InfiniteScrollingID") === null) {
whereToAddIt.insertAdjacentHTML("afterend", "<div id='InfiniteScrollingID'></div>");
}
for (let i= 0; i < howManySitesPerLoad; i++) {
code= `${eval(`siteTitle${i}`)}\n</br></br></br>`
document.getElementById("InfiniteScrollingID").insertAdjacentHTML("beforeend", code);
}
for (var i=0; i < howManySitesPerLoad; i++) {
sitesOnPage.push(eval(`randomSite${i}`))
}
brLength= document.querySelectorAll("br").length;
whereToAddIt= document.querySelectorAll("br")[brLength-1];
observer.disconnect()
observer.observe(whereToAddIt)
}
This is a re-post since nobody answered me before when i provided a working minimal example and this script is super important for my site.
This is part of code that is used for my site in its sections, http://www.coolwebsites.ml/
https://youtu.be/QDrn_9svt6Y
CodePen: https://codepen.io/Attisalva/pen/pojdZXr?editors=1010
In the CodePen example (same problem), it creates (in this case title names to simplify the code) some title names that are already on the page and it should only create titles that aren't yet created (you can find titles in the object "infiniteResponseAAA").
I'm trying to lazy loading new images, titles, descs, etc randomly on the page but it keeps creating without checking properly if everything is already on page.
It's because i didn't end/return the function after i got a good number

How do I style this code using html and css?

The code below is for listing blogger posts within a Label Name, if the post has the specific Label Name it will be shown in this list. I would like to be able to change the appearance of how everything is displayed by changing where the post image would look, and where the title would look, change background color, add borders, shadows change the font etc ...(I know how to change the appearance with css, but I do not know how to integrate the code below with css and html) At the moment the code shows the title and the right of the title the image.
var startIndex = 1;
var maxResults = 5;
var allResults = [];
function sendQuery12()
{
var scpt = document.createElement("script");
scpt.src = "https://levon-ltr.blogspot.com//feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root)
{
//Sort Alphebetically
allResults.sort(function(a, b){
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root)
{
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0)
{
for (var i = 0; i < feed.entry.length; i++)
{
var entry = feed.entry[i];
var title = entry.title.$t;
var date = entry.published.$t;
if( entry.media$thumbnail != undefined ){
var imageThumb = entry.media$thumbnail.url ;
} else {
var imageThumb = 'https://i.imgur.com/PqPqZQN.jpg' ;
}
for (var j = 0; j < entry.link.length; j++)
{
if (entry.link[j].rel == "alternate")
{
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0)
{
var liE = document.createElement("li");
var a1E = document.createElement("a");
var postImage = document.createElement("img");
a1E.href = url;
a1E.textContent = title;
postImage.src = imageThumb;
liE.appendChild(a1E);
liE.appendChild(postImage);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults)
{
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
<div>
<ul id="postList12"></ul>
</div>
This creates stuff you can style with CSS. For example:
#postList12 li {
border: 1px solid blue;
}
Use the inspector in your browser to see what it makes. If you want to change the order of elements or add new ones you’ll have to edit the script to do that.

How can I get the text to which a Nested Style is applied in InDesign

I am trying to write a script that will convert all characters to lowercase if a particular nested style is applied. I can't seem to figure out the correct syntax to get the text.
I originally tried the following, which worked to an extend, but lowercased the entire paragraph rather than only the text that has the character style applied:
function lowerCaseNest(myPStyle, myCStyle){
var myDocument = app.documents.item(0);
//Clear the find/change preferences.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeTextOptions.caseSensitive = false;
app.findChangeTextOptions.includeFootnotes = false;
app.findChangeTextOptions.includeHiddenLayers = false;
app.findChangeTextOptions.includeLockedLayersForFind = false;
app.findChangeTextOptions.includeLockedStoriesForFind = false;
app.findChangeTextOptions.includeMasterPages = false;
app.findChangeTextOptions.wholeWord = false;
app.findTextPreferences.appliedParagraphStyle = myPStyle;
var missingFind = app.activeDocument.findText();
var myDoc = app.documents[0];
for ( var listIndex = 0 ; listIndex < missingFind.length; listIndex++ ) {
for (i = missingFind[listIndex].nestedStyles.length-1;i>=0; i--) {
for (j = missingFind[listIndex].nestedStyles[i].parent.characters.length-1;j>=0; j--) {
if (missingFind[listIndex].nestedStyles[i].parent.characters[j].contents.appliedCharacterStyle(myCStyle)) {
var myString = missingFind[listIndex].nestedStyles[i].parent.characters[j].contents;
if (typeof(myString) == "string"){
var myNewString = myString.toLowerCase();
missingFind[listIndex].nestedStyles[i].parent.characters[j].contents = myNewString;
}
}
}
}
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
}
I then tried playing around with appliedNestedStyles, but can't seem to figure out how to retrieve the text that the nested style is applied to.
Could anyone help with this?
Thanks!
John
Unless I am wrong the appliedNestedStyle can be looked after in the F/C dialog by targeting the applied characterStyle:
GREP
Find : .+
Format : character style => myCharStyle
then
var found = doc.findGrep();
…
I actually took a different tack, and figured out something that works:
function lowerCaseNest(myPStyle, myCStyle){
for (var i = 0; i < app.activeDocument.stories.length; i++){
for (var j = 0; j < app.activeDocument.stories[i].paragraphs.length; j++){
var myP = app.activeDocument.stories[i].paragraphs[j];
if (myP.appliedParagraphStyle.name==myPStyle) {
for (k=0; k<myP.characters.length; k++) {
if(typeof(myP.characters[k].appliedNestedStyles[0]) != 'undefined'){
if(myP.characters[k].appliedNestedStyles[0].name == myCStyle) {
var myC = myP.characters[k].contents;
if (typeof(myC)=='string'){
var myNewString = myC.toLowerCase();
myP.characters[k].contents = myNewString;
}
}
}
}
}
}
}
}
Still would be interested in knowing if there's an easier way to handle this, as I'm afraid this may take longer to run on long documents, since it's dealing with every paragraph individually.

Illustrator Script: Export Single Layer to SVG

I have been trying to get a script going that is able to export a specific illustrator file to a SVG format. I have been referencing this Adobe forum post about a method of doing this and implemented it somewhat succesfully, see below:
var singleLayer,
doc,
path = 'C:/Users/lukeb/Desktop/New folder',
type = ExportType.SVG,
options = new ExportOptionsSVG(),
layerAmount;
doc = this.myApp;
singleLayer = this.myApp.layers["buttons"];
options.embedRasterImages = false;
options.cssProperties = SVGCSSPropertyLocation.PRESENTATIONATTRIBUTES;
options.fontSubsetting = SVGFontSubsetting.None;
options.documentEncoding = SVGDocumentEncoding.UTF8;
options.coordinatePrecision = 4;
layerAmount = doc.layers.length;
hideAllLayers();
for (var i = layerAmount - 1, k = 0; i >= 0; i--, k++) {
if (this.myApp.layers[i] === singleLayer) {
var file;
singleLayer.visible = true;
file = new File(path + "/" + singleLayer);
this.myApp.exportFile(file, type, options);
singleLayer.visible = false;
}
}
showAllLayers();
function hideAllLayers() {
for(var i = 0; i < layerAmount; i++) {
doc.layers[i].visible = false;
}
}
function showAllLayers() {
for(var i = 0; i < layerAmount; i++) {
doc.layers[i].visible = true;
}
}
This code runs perfectly, to an extent. It singles out the layer in my layer library and turns all of them off except that one. But for some reason it does not export just that one layer as an SVG, it exports a whole lot, if not all of them. Is there something missing with this? There isnt a lot of documentation around all of this so wasnt too sure of a fool proof solution to just get a single layer.

Categories

Resources