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>
Related
I want something like that..
https://pl.sports-streams-online.best/?st=nbastream.tv&plcm=db&q=Raptors+vs+Lakers
See that URL part q=Raptors+vs+Lakers, If i input any text on this section it will automatically change on website body. I want to know how i can do this. I will input a text in URL and it will display on website body.
Thanks for advance.
You can parse window.location and put that into a div on your page. I can't show you in a code snippet because the snippets use an iframe but if your html has <div id='uText'></div> then you can use javascript (after the page has loaded) to set the value of that div with results of the query param. lets say your url ends in ?st=nbastream.tv&plcm=db&q=Raptors+vs+Lakers, then you want the value for parameter 'q':
function getQueryStringParam(param) {
var url = window.location.toString();
url.match(/\?(.+)$/);
var params = RegExp.$1;
params = params.split("&");
var queryStringList = {};
for(var i = 0; i < params.length; i++) {
var tmp = params[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}
return decodeURIComponent(queryStringList[param]);
}
let qParam = getQueryStringParam('q').split('+').join(' ');
const div = document.getElementById('uText');
div.innerHTML = qParam;
Check out the codepen here.
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.
I'm trying to create a script that will make it easier for users to use a custom button and I have something like
<script src="http://host.com/file.js?id=12345"></script>
What I wonder is how can I, in the file.js get that id parameter.
if I use document, it will get the original html page that has the script line and what I need is that id.
is there any way i can get that id successfully? What should be the scope?
added
the idea is that I can have several buttons in the page for example to have a small and simply list:
<ul>
<li><script src="http://host.com/file.js?id=12345"></script></li>
<li><script src="http://host.com/file.js?id=23456"></script></li>
<li><script src="http://host.com/file.js?id=34567"></script></li>
</ul>
this will ultimately translate to
<ul>
<li><a class="view40btn" href="#" data-id="12345"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="23456"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="34567"><strong>V40</strong> Watch the video</a></li>
</ul>
the list above will look like this in HTML:
My only issue is that I can't assign the correct id to the data-id attribute as this is generated in the file.js.
result
from Paulpro answer I got it working with his idea and knowing that the client will have much more scripts loaded and several with id's I changed it a bit for the final and working version:
var id = (function(){
var scripts = document.getElementsByTagName('script');
for(var i = 0, result = {}; i < scripts.length; i++)
if(scripts[i].hasAttribute('data-viewfileid'))
result['id'] = decodeURIComponent(scripts[i].getAttribute('data-viewfileid'));
return result['id'];
})();
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
the script for the user would only be:
<script data-viewfileid="4444" src="file.js" type="text/javascript"></script>
You can get the last script element on the page (which will always be the currently executing one):
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
Then modify one of the query string parsers from this question to work with that scripts src property:
var url = s.src;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][2]);
}
That will give you an object containing all the query string properties on the current script. You can just access the properties like:
result['id']; // '12345'
In summary
To get the id parameter from within file.js, add the following code to the top of file.js:
var id = (function(){
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
var qs = s.src.substring(s.src.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][3]);
}
return result['id'];
})();
Make sure it is not in any callback functions like a DOMReady callback.
Edit: You can probably reduce your script to:
var scripts = document.getElementsByTagName('script');
var id = scripts[scripts.length - 1].getAttribute('data-viewfileid');
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
JavaScript doesn't know anything about the script tag that loaded it. However, there are a few workarounds.
If the file is being preprocessed on the server, you could make the server render the value in the response:
(function() {
var id = <%= params.id %>;
//other stuff here
}());
Or you could give the script tag an id, and make your code find it and pull out the URL.
HTML:
<script src="http://host.com/file.js?id=12345" id="myscript"></script>
JS:
var id = document.getElementById('myscript').split('id=')[1];
Or in modern browsers you could perhaps do something like this to find script tags that match where you know the script is.
var scriptTag = document.querySelector('script[src^="http://host.com/file.js"]');
var id = scriptTag.src.split('id=')[1];
One more solution is to parse .js files with php interpreter. For example in apache configuration:
AddType application/x-httpd-php .js
And in JS:
alert('<?=$_GET["id"]?>');
You can put an ID on anything, including a script tag. So you can do something like this:
HTML:
<script id="myScript" src="http://host.com/file.js?id=12345"></script>
JS:
document.getElementById('myScript').src.split('=')[1]; to get the ID from that particular example string.
If that query string represents a timestamp (in which case you need the latest version) you can modify the JavaScript code to fetch the latest <script> tag like so:
var scripts = document.getElementsByTag('script');
var latestScriptId = scripts[scripts.length-1].src.split('=')[1];
EDIT: In the context of your new edit, you would then take latestScriptId and assign it to the data.id attribute corresponding to the button you would like to create...though again, semantically, it would just make more sense to use HTML's given id attribute, and additionally, since you are not using the href property for the anchor <a> tag, you're better off using a <button> element. So something like this would suffice:
var myButton = document.createElement('button');
myButton.className += 'view40btn';
myButton.id = latestScriptId;
According to your clarifications, what you asking how to do is not what you want to do.
Instead, include one script, and have multiple placeholder nodes.
HTML:
<ul>
<li class="mybutton" data-id="12345"></li>
<li class="mybutton" data-id="23456"></li>
<li class="mybutton" data-id="34567"></li>
</ul>
<script src="myscript.js"></script>
JS:
// myscript.js
var buttons = document.getElementsByClassName('mybutton');
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.innerHTML = "my button html template here with id: "+ button.dataset.id;
}
See it work here: http://jsfiddle.net/zAdnB/
Javascript code does not "realise", that it is a part of some file. JS file is not "executable", there is no main method, which should be run after loading the file. You can not pass GET parameters to it - it is not clear how they should be interpreted.
In your HTML page, you should listen to "onload" method and then call the function from your file with your parameter.
I got an HTML string as :var code; I want to extract all hyper link title values in this big string and place them in textarea. I tried the following but it never works. could any one tell me what i am doing wrong?
sample hyperlinks to look for(i want to extract mango,cherry,...) :
mango
cherry
my code string has blocks of data like below:
<div class="details">
<div class="title">
mango
<span class="type">3</span>
</div>
</div>
full code:
$.getJSON('http://anyorigin.com/get?url=http://asite.com/getit.php/&callback=?', function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
var start = siteContents.indexOf('<ul class="list">');
var end = siteContents.indexOf('<ul class="pag">', start);
var code = siteContents.substring(start, end);
document.myform2.outputtext2.value = code ;
var pattern = /<a href="([^"]+?)">([^<]+?)<\/a>/gi;
code = code.match(pattern);
for (i = 0; i < code.length; i++) {
document.write($2<br />'));
}
});
</script>
It looks like you're trying to parse HTML with regex. This post has some more info on that topic.
Since this question is tagged as jQuery, you could try something like the following...
Make a jQuery object out of the returned HTML:
$markup = $(data.contents);
Find the anchors:
$anchors = $markup.find('a');
Get the text (or whatever attribute you want from it):
arrText = [];
$anchors.each(function() {
arrText.push($(this).text());
});
Put result into textarea:
$textarea.val(arrText.join(','));
To achive this jquery is the simplest solution, you can try below code
$('a').each(function(){
var copiedTitle = $(this).html();
var previous = $('#test').html();
var newText = previous +"\n"+ copiedTitle;
$('#test').html(newText);
});
JS Fiddle
I'm trying to get this JavaScript working:
I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.
<!-- ORIGINAL DIV -->
<div id="Email">
</div>
<!-- DIV replacement function -->
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';
ReplaceContentInContainer('Email1',content);
}
</script>
<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';
ReplaceContentInContainer('Email2',content);
}
</script>
Any ideas what I've done wrong that is causing it not to work?
Rather than inserting the element as text into innerHTML create a DOM element, and append it manually like so:
var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"
document.getElementById("email").appendChild(obj);
See this working here: http://jsfiddle.net/BE8Xa/1/
EDIT
Interesting reading to help you decide if you want to use innerHTML or appendChild:
"innerHTML += ..." vs "appendChild(txtNode)"
The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.
As for grabbing the content parameter from the query string:
var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".
With the closing "}", you are closing a block of code you never opened.
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:
<script type="text/javascript">
function ParseQueryString() {
var result = new Array();
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
</script>
Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:
<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var contentId = QS["content"];
if (contentId) {
var source = document.getElementById(contentId);
if (source) {
var target = document.getElementById("Email");
target.innerHTML = source.innerHTML;
}
}
}
How about this? Hacky but works...
<!-- ORIGINAL DIV -->
<div id="Email"></div>
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}
window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>