Changing link suffix with javascript on keypress - javascript

I'm new to Javascript, so bear with me. Let's say I have this link: example.com/img/000.png/. It displays an image source, so I'll put it in an image tag. <img src="example.com/img/001.png/">.
When I press a key (right arrow, for example), the link should change (inside the image tag) to example.com/img/001.png/, /002.png/, /003.png/, etc. is is possible, at all, to do this with Javascript, embedded in the raw HTML?
Here are my thoughts so far:
<img src=" <!-- Link generated by Javascript --> ">
<script>
// actually pythonic pseudocode, ok
counter = 0
if (right arrow key pressed):
counter = counter + 1
counterPrep = (3-len(counter))*'0'+str(counter)
// ^^^ changes the link from "1" to "001"
link = "https://www.example.com/img/"+str(counterPrep)+".png
</script>
I know what I'm asking may be unclear, so feel free to ask questions. I usually work in Python, which is why the pseudocode is so "Pythonic".
Thanks!

You can detect the key press of the user using the event called keypress.
The rigth arrow key has a key code 39, so you can do the following :
<img src="example.com/img/001.png" id="myImage">
<script>
var counter = 0;
document.body.addEventListener("keypress", function(e){
if(e.keyCode==39) {
counter ++;
var index = (("00" + counter).slice(-3));
var link = "https://www.example.com/img/"+index+".png";
document.getElementById('myImage').src = link;
}
});
</script>

Please see the snippet below:
document.getElementById("testBtn").onclick = function() {
var imgSrc = document.getElementById("dynamicImg").src;
var start = imgSrc.lastIndexOf("/") + 1, end = imgSrc.lastIndexOf("/") + 4;
var preUrl = imgSrc.substring(0, start);
var postUrl = imgSrc.substring(end, imgSrc.length);
// get the fileName
var imgName = parseInt(imgSrc.substring(start, end)) + 1;
// convert to 000 format
imgName = ("00" + imgName).slice(-3);
// replace img src
document.getElementById("dynamicImg").src = preUrl + imgName + postUrl;
alert(document.getElementById("dynamicImg").src)
};
<img id="dynamicImg" src="example.com/img/000.png" />
<button id="testBtn">
TEST
</button>
The code above will work using dynamic url.
I tried it using onclick button, but you can change the event ti keypress.
I hope this helps.

Related

Replace elements in a link using javascript

I have a link to add event to google calendar which is populated from a database, but the date is formatted yyyy-mm-dd, and the time hh:mm, and i cannot alter this, but google calendar will not accept.
Can anyone please help me use javascript and the 'replace' function to remove the'-' and ':' from the html please?
<a href="http://www.google.com/calendar/event?
action=TEMPLATE
&text=Tester12
&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z
&details=Oranges
&location=Newquay
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>
many thanks.
Fetch the href link from tag and store it in a variable.
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Tester12&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z&details=Oranges&location=Newquay&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
This will remove all the '-' and ':' from dates parameter string and will store that link in 'finalLink' var.
Hope it helps.
I have been on the sniff for the whole code solution, and witha bit of mix and match, came up with this, AND IT SEEMS TO WORK!!!!!! But please feel free to edit into perfection!
<script>
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Example Event&dates=2018-12-16T10:3500Z/2018-12-16T12:0000Z&details=Trip to town&location=No mans land&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
</script>
Add Event
<script>
(function() {
Array.prototype.forEach.call(document.querySelectorAll("a.finalLink"), function(link) {
link.href = finalLink;
});
})();
</script>

text string output stops after first space, js/html

I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>

Displaying the filename of a HREF in Javascript

I have a page with a download button like this:
<a href="http://www.example.nl/filename.pdf" download>DOWNLOAD</a>
Below, I want (text) to automatically display "filename.pdf" (rather than having to do this by hand hundreds of times).
I found the script below that displays the filename of the PAGE but I want it to display the FILENAME of a HREF I've used on the actual page.
Any help is much appreciated.
<script type="text/javascript">
var segment_str = window.location.pathname;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.write(last_segment);
</script>
Thanks in advance!
Not sure where you want the "text" to display... so I put it in a div
<a href="http://www.example.nl/filename.pdf" download>DOWNLOAD</a>
<div id="result">
</div>
The big change, is to get all the "a" tags, using getElementsByTagName... and then iterating over the list, and then you can use the string split, and pop off the last segment before appending it to a destination.
var input = document.getElementsByTagName('a');
for(i = 0;i < input.length; i++)
{
var segment_str = input[i].href;
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
document.getElementById("result").innerText += last_segment;
}
Maybe this will help.
<div id=download1></div>
<script>
var filename = 'example.pdf';
$('#download1').html('' + filename + '');
</script>

jQuery insert/remove text at specific position in input field/textarea

I am trying to do similar thing as YouTube has when you are embeding a video and you want to get a code. You can click on checkboxes or select size and it dynamically changes the value of input field.
Does somebody have idea how to do it?
I managed to write a code that is replacing the width correctly, but I dont know how to make a code that would add &scheme=XXX at the end of the link or remove it if user selects no color scheme.
This is the code for width,I dont think its best one, but works:
$("#width").on("change keyup", function(){
var width = $(this).val();
if (width){
$("#embed-text").val($("#embed-text").val().replace(/ (width\s*=\s*["'])[0-9]+(["'])/ig, ' width=\''+width+'\''));
}
});
Here is textarea which I am trying to change and inputs I'm using for it:
The ID is taken from PHP, in actual textarea that jQuery sees the ".$id." is actual number
<textarea class='clean' id='embed-text'><iframe src='http://my.url/embed/?r=".$id."' width='600' height='".$height."' frameborder='0' marginwidth='0' marginheight='0' allowtransparency='true'></iframe></textarea>
<div style='padding-right: 10px; display: inline-block;'>
Color scheme:
<select id='schemes' class='clean'>
<option value='-'>None</option>
<option value='xxx'>Xxx</option>
</select>
</div>
<div style='padding-right: 10px; display: inline-block;'>
Width: <input type='number' min='250' max='725' value='600' id='width' class='clean'>
</div>
When user does not select any scheme (or changes from XXX to None), I want link in textarea (iframes src) to be like this:
http://my.url/embed/?r=X
But when he selects any scheme, i would like it to look like this:
http://my.url/embed/?r=X&scheme=XXX
I actually have no idea how to do this. Tried googling for more than hour, but I don't know what the ID will be (to identify position where to add the string), thats PHP value and I cant pass it to external script file, so I tried to find if I can insert something at specific position (ie.: 15th character from start) with JS, but could not find anything.
Thanks.
I separate some functions in order to keep the code clean check this I think that is what you were looking for JsFiddle
var generateUrl = function(id,colorScheme) {
var baseUrl = "http://my.url/embed/?";
var url = baseUrl.concat("r="+id);
if (colorScheme != null && colorScheme != '')
url = url.concat("&scheme="+colorScheme);
return url;
};
var changeUrl = function(id, colorScheme) {
var url = generateUrl(id, colorScheme);
var srcPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(srcPattern),"src='"+url+"'");
$("#embed-text").val(newEmbedText);
};
var changeWidth = function(newWidth) {
var widthPattern = "width='([0-9]*)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(widthPattern),"width='"+newWidth+"'");
$("#embed-text").val(newEmbedText);
};
var getURLParameter = function(url,parameterName) {
return decodeURIComponent((new RegExp('[?|&]' + parameterName + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null
};
var getId = function() {
var urlPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var url = embedText.match(new RegExp(urlPattern))[1];
var id = getURLParameter(url, 'r');
return id;
};
$("#width").on("change keyup", function(){
var width = $(this).val();
var colorScheme = $(schemes).val();
changeWidth(width);
changeUrl(getId(),colorScheme);
});
And i removed the value '-' for the first option just leave it in blank.

Extracting the source code of a facebook page with JavaScript

If I write code in the JavaScript console of Chrome, I can retrieve the whole HTML source code by entering:
var a = document.body.InnerHTML; alert(a);
For fb_dtsg on Facebook, I can easily extract it by writing:
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
Now, I am trying to extract the code "h=AfJSxEzzdTSrz-pS" from the Facebook Page. The h value is especially useful for Facebook reporting.
How can I get the h value for reporting? I don't know what the h value is; the h value is totally different when you communicate with different users. Without that h correct value, you can not report. Actually, the h value is AfXXXXXXXXXXX (11 character values after 'Af'), that is what I know.
Do you have any ideas for getting the value or any function to generate on Facebook page.
The Facebook Source snippet is below, you can view source on facebook profile, and search h=Af, you will get the value:
<code class="hidden_elem" id="ukftg4w44">
<!-- <div class="mtm mlm">
...
....
<span class="itemLabel fsm">Unfriend...</span></a></li>
<li class="uiMenuItem" data-label="Report/Block...">
<a class="itemAnchor" role="menuitem" tabindex="-1" href="/ajax/report/social.php?content_type=0&cid=1352686914&rid=1352686914&ref=http%3A%2F%2Fwww.facebook.com%2 F%3Fq&h=AfjSxEzzdTSrz-pS&from_gear=timeline" rel="dialog">
<span class="itemLabel fsm">Report/Block...</span></a></li></ul></div>
...
....
</div> -->
</code>
Please guide me. How can extract the value exactly?
I tried with following code, but the comment block prevent me to extract the code. How can extract the value which is inside comment block?
var a = document.getElementsByClassName('hidden_elem')[3].innerHTML;alert(a);
Here's my first attempt, assuming you aren't afraid of a little jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var html = $('.hidden_elem')[0].innerHTML.replace('<!--', '').replace('-->', '');
var href = $(html).find('.itemAnchor').attr('href');
var fbId = getParameterByName('h', href); // fbId = AfjSxEzzdTSrz-pS
Working Demo
EDIT: A way without jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var hiddenElHtml = document.getElementsByClassName('hidden_elem')[0]
.innerHTML.replace('<!--', '').replace('-->', '');
var divObj = document.createElement('div');
divObj.innerHTML = hiddenElHtml;
var itemAnchor = divObj.getElementsByClassName('itemAnchor')[0];
var href = itemAnchor.getAttribute('href');
var fbId = getParameterByName('h', href);
Working Demo
I'd really like to offer a different solution for "uncommenting" the HTML, but I stink at regex :)

Categories