Can I pass a URL as a variable? - javascript

I have the following script that is not giving me the result I want. JSFiddle link at the bottom.
Note: This is not my image. I grabbed it randomly from imgur.
I expect:
<img src="https://i.imgur.com/MiOeWrk.jpg" style="max-width:800px;">
But I get this, I believe, but I'm unable to write this in a code block while debugging, for some reason.
<img src="http://thisismydomain.com/https://i.imgur.com/MiOeWrk.jpg" style="max-width:800px;">
Here's my script. Please advise:
<div>Show Image</div>
<div id="jsdebug">jsdebug</div>
<div id="video_aba">video_aba</div>
<script>
function viewimage(ytlink, uid) {
var imagelink = ytlink;
document.getElementById("jsdebug").innerHTML = imagelink;
var uid = uid;
if (imagelink.length == 0) {
imageembed = "<strong>Sorry, unable to load.</strong>";
} else {
imageembed = "<img src=\"/" + imagelink + "\" style=\"max-width:800px\">";
}
document.getElementById("video_aba").innerHTML = imageembed;
}
</script>
https://jsfiddle.net/gde5630h/

The problem is what your image link coded . It's like this imageembed = "<img src=\"/" + imagelink + "\" style=\"max-width:800px\">";
/ => this will prepend to your current domain url eg.if your domain is localhost it will goes localhost/https://i.imgur.com/MiOeWrk.jpg
So remove / from your image link

Your attribution is not correct. href should be replaced with onclick event.
"href" is not used for javascript events. It is used to link the webpages.
javascript events are onclick, onhover, onmouseenter, etc.
function viewimage(ytlink, uid) {
var imagelink = ytlink;
var uid = uid;
if (imagelink.length == 0) {
imageembed = "<strong>Sorry, unable to load.</strong>";
} else {
imageembed = `<img src="${ytlink}" style="width:800px">`;
}
document.getElementById("video_aba").innerHTML = imageembed;
document.getElementById("jsdebug").innerText = imageembed;
}
a {
color: blue;
text-decoration: underline;
cursor: pointer;
}
<div>Show Image</div>
<div id="jsdebug">jsdebug</div>
<div id="video_aba">video_aba</div>

Related

search result won't automatically display

i have building a Giphy Gif search app through giphy API and it works fine just each time when i tried to type something new in the search text and the new search result won't pop out unless i reload the page.
the HTML code as following:
<html>
<head>
<title>My Giphy Search App</title>
<style>
.container-image {
width: 30%;
display: inline-block;
float: left;
margin-right:3%;
}
</style>
</head>
<body>
<div class="container container-padding50">
<input type="text" class="js-userinput container-textinput" placeholder="refresh the page if you wanna searching more">
<button class="js-go container-button">Go!</button>
</div>
<div class="js-container">
</div>
<script src ="javascript/main.js"></script>
</body>
the js code in main.jsfile as:
document.querySelector(".js-go").addEventListener("click",function(e){
var input = document.querySelector("input").value;
searchGiphy(input);
});
document.querySelector(".js-userinput").addEventListener("keyup",function(e){
var input = document.querySelector("input").value;
if(e.which == 13){
searchGiphy(input);
}
});
function searchGiphy(searchResult){
var url = "http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q=" + searchResult;
var GiphyAJAXCall = new XMLHttpRequest();
GiphyAJAXCall.open("GET",url);
GiphyAJAXCall.send();
GiphyAJAXCall.addEventListener("load",function(e){
var data = e.target.response;
pushToDOM(data);
});
}
function pushToDOM(input){
var response = JSON.parse(input);
var imageUrls = response.data;
var container = document.querySelector(".js-container");
imageUrls.forEach(function(image){
var src = image.images.fixed_height.url;
container.innerHTML += "<img src=\"" + src + "\" class=\"container-image\">";
});
}
I am pasting all the js code above and wondering am i wrong with the ajax calling here? Could some one help me with this?
You are appending the results to the end of the current html instead of replacing what is already there. Instead use another variable to build the new html string you are constructing and then when you are done replace the innerHTML of the container with the new string.
function pushToDOM(input){
var response = JSON.parse(input);
var imageUrls = response.data;
var container = document.querySelector(".js-container");
var html = "";
imageUrls.forEach(function(image){
var src = image.images.fixed_height.url;
html += "<img src=\"" + src + "\" class=\"container-image\">";
});
container.innerHTML = html;
}

How to execute javascript function with the pre-put string from database

I want to run a javascript function with the pre loaded text from database. This function is about to display the image from youtube. Once a pasted link is correct. It will show the thumbnail automatically.
But I want a picture to display with the pre-text link from a database.
Here is the function :
function youtube_parser(url) {
var regExp = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[1].length == 11) {
urllink = match[1];
imagelink = "<img src=\"http:\/\/img.youtube.com\/vi\/"+urllink+"\/hqdefault.jpg\">";
} else {
//urllink = "test"
}
document.getElementById("ytimagelink").value = urllink;
document.getElementById("ytimage").innerHTML = imagelink;
}
HTML
<div><strong>Insert YouTube url:</strong></div>
<input type="text" id="ytlink" onkeyup="youtube_parser(this.value)">
<hr>
<div><strong>Output: YouTube video id:</strong></div>
<input type="text" id="ytimagelink" value="">
<div><strong>Output: Thumbnail</strong></div>
<div id="ytimage"></div>
Fiddle : http://jsfiddle.net/PMrLR/7/
This function will work as I put the url in #ytlink because there is a onKeyUp property to trigger the function.
So, I expect this function to work with the pre-loaded text without doing anything to it again.
Your function will work as it is, just give it the text you loaded from the database as it's argument:
// ...get data from the database somehow, and then:
youtube_parser(url_from_database);
You'll have to wait for the document to load first, and then call the youtube_parser(yourUrl). Do it like this in VanillaJS
document.addEventListener("DOMContentLoaded", function() {
youtube_parser('https://www.youtube.com/watch?v=OnXTf8FNUrc');
});
Here is the snippet for you, show it and click run button
function youtube_parser(url) {
var regExp = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[1].length == 11) {
urllink = match[1];
imagelink = "<img src=\"http:\/\/img.youtube.com\/vi\/" + urllink + "\/hqdefault.jpg\">";
} else {
//urllink = "test"
}
document.getElementById("ytimagelink").value = urllink;
document.getElementById("ytimage").innerHTML = imagelink;
}
document.addEventListener("DOMContentLoaded", function() {
youtube_parser('https://www.youtube.com/watch?v=OnXTf8FNUrc');
});
body {
font-family: arial, helvetica, sans-serif;
font-size: 18px;
}
<div><strong>Insert YouTube url:</strong>
</div>
<input type="text" id="ytlink" onkeyup="youtube_parser(this.value)">
<hr>
<div><strong>Output: YouTube video id:</strong>
</div>
<input type="text" id="ytimagelink" value="">
<div><strong>Output: Thumbnail</strong>
</div>
<div id="ytimage"></div>

How to check what the last dynamically added element was and run a Particular Function

I am trying to write a code for a chat application. What I want is, When someone types something and clicks on send, I want to add a 'row' (dynamically) inside a container called 'chat'. The 'row' contains the message in another container called 'message' (which is also created dynamically). I was able to do that. But what I want to do is this, when someone types two message in a row (i mean before getting any reply from the person he/she is chatting with) and hits send I don't want add an entire 'row' in the 'chat'. I just want to append the 'message' inside the row, something like :
$('button').on('click', function() {
if(last added element was .row.user) {
$('.row').appnd('<div class="message">/div>');
} else {
}
});
Is there anyway to achieve what I described is pseudo code?
here is the HTML
<div class="chat">
<div class="row">
<div class="message"></div>
</div>
</div>
This can be done like this:
function addMessage(message, user) {
chat = $("#chat"); //Get a reference to the chat div.
lastRow = chat.find(".row:last"); //Get a reference to the last row of the chat.
if(lastRow.attr("data-user") == user) {
//Its the same user who posted last time.
lastRow.append("<div class='message'>" + message + "</div>");
}
else {
//It's a different user.
chat.append('<div class="row" data-user="' + user + '"><div class="message">' + message + '</div></div>');
}
}
Working JSFiddle.
What about this:?
<html>
<head>
<style>
.row{
border: 1px solid;
padding: 5px;
margin: 5px;
}
</style>
</head>
<body>
<div class="chat"></div>
Message: <input type="text" id="message"/>
<br/><br/>
<button onclick="sendMessage('userA');">Send Message as User A</button>
<button onclick="sendMessage('userB');">Send Message as User B</button>
<script>
var lastUser = null;
function sendMessage(user){
var chat = document.querySelector('.chat');
var message = document.getElementById('message');
if(user != lastUser){
var newRow = document.createElement('div');
newRow.className = 'row';
var newMessage = document.createElement('div');
newMessage.className = 'message';
newMessage.innerHTML = '<strong>' + user + '</strong><br/>';
newMessage.innerHTML += message.value;
newRow.appendChild(newMessage);
chat.appendChild(newRow);
lastUser = user;
}else{
var rows = document.querySelectorAll('.chat .row');
var lastRow = rows[rows.length - 1];
var lastMessage = lastRow.querySelector('.message');
lastMessage.innerHTML += '<br/>' + message.value;
}
message.value = '';
}
</script>
</body>
</html>

How to export a auto generated HTML to PDF

I have the following code which is partially what my HTML page does.
<script>
function close() {
MainJavaScript();
}
function MainJavaScript()
{
//var strEntity = " ";
var strEntity = document.getElementById('Entity').value;
//Images setup by Entity
if (strEntity == "MGP")
{
document.getElementById('displayPic').src="http://mgp75.png";
}
else if (strEntity == "MPP")
{
document.getElementById('displayPic').src="http://mpp75.png";
}
else if (strEntity == "RSC")
{
document.getElementById('displayPic').src="http://rsc75.png";
}
else if (strEntity == "MSN")
{
document.getElementById('displayPic').src="http://msn75.png";
}
var strFirstName = "John";
var strLastName = "Doe";
var strSuffix = " ";
var strTitle = "DDS";
var strSecondaryTitle = " ";
var strDisplayName = strFirstName + " " + strLastName;
if (strTitle.trim() != '')
strDisplayName += ", " + strTitle;
if (strSuffix.trim() != '')
strDisplayName += ", " + strSuffix;
if (strSecondaryTitle.trim() !='')
strDisplayName += ", " + strSecondaryTitle;
document.getElementById('FullName').innerHTML = strDisplayName;
}
</script>
Submit
<table>
<tr>
<td width="55%">
<div class="first">
<div class="contact-info">
<h3><img id="displayPic" src="" alt=""></h3>
</div><!--// .contact-info -->
</div>
</td>
<td width="40%">
<div>
<h1><font color="#003893" face="Georgia">Cu Vi</font></h1>
<h2><span id="FullName"></span></h2>
</div>
</td>
</tr>
</table>
When I click the Submit button the displayPic and the FullName is replaced by the respective values using MainJavascript function. What I am looking to do is create a PDF from the output but unfortunately all the DLLs and method I found requires me to output a HTML file and then convert to a PDF but because it is using JavaScript, the source is always blank but the display is changed once the button is clicked.
How can I achieve what I am looking to do, is convert the output into a PDF?
You should look at Xep CloudFormatter. This library, jquery plugin, prints any html page. So, given your example, if I were to start with an HTML template like you have, and then with javascript/jquery I populate the html and then call xepOnline.Formatter.Format to render it, you will get back a beautiful PDF.
I simplified your code a bit, but here is a fiddle for you to explore:
http://jsfiddle.net/kstubs/56x6W/
function printMe() {
tryAtMain();
var imgLoad = imagesLoaded($('#displayPic')[0]);
imgLoad.on( 'always', function() {
xepOnline.Formatter.Format('print_me', {
pageMargin: ".25in"
});
});
}
function tryAtMain() {
// some pic
$('#displayPic').attr('src','http://lorempixel.com/output/abstract-q-c-370-222-1.jpg');
$('#FullName').html('Johnny Carson');
}

If / Else in DIV statement?

First, I am not a programmer anymore... It's been years since doing it and even then it was only VBA and old school HTML.
What I would like to do is to show an image on my site in place of another depending on it's "state". For example, the site is http://w2zxl.hevener.com/ , towards the bottom of the page is a script that loads a HAM radio logbook as well as my current status in nearly real time. If I am on the Air, it will show a small image that says "On Air" and then show what frequency I am on and the Mode I am working in. When I am off the air however, that little image just disappears and shows nothing.
What I would like to do is to create a small image to replace the "nothing". In other words, if I am Off Air, I would like to show an "Off Air" image instead of nothing at all.
Is there an If/Then/Else statement that can do this given the code I am providing below?
Code below:
<!-- HRDLOG.net script start --><center>
<div id="hrdlog-oa"> </div>
<div id="hrdlog">www.hrdlog.net</div>
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
<script type="text/javascript" language="javascript">// <![CDATA[
var ohrdlog = new HrdLog('W2ZXL');
setInterval('ohrdlog.LoadOnAir()', 5000);
ohrdlog.LoadLastQso(10);
// ]]></script>
<img src="http://www.hrdlog.net/callplate.aspx?user=W2ZXL" alt="W2ZXL CallPlate" /></center><!-- HRDLOG.net script stop -->
Consider swapping CSS classes to change the background-image instead. This will simplify the javascript and html markup. When you're on air change the class to onair and toggle as needed to offair.
CSS
.onair {
background-image: url("onair.jpg");
}
.offair {
background-image: url("offair.jpg");
}
Html
<div id="hrdlog-oa" class="offair"></div>
Javascript
var statusDiv = document.getElementById("hrdlog-oa");
if (statusDiv.className == "offair") {
statusDiv.className = "onair";
}
else {
statusDiv.className = "offair";
}
Working jsfiddle http://jsfiddle.net/jasenhk/qMAZU/ using background-color instead.
You can not do that with pure HTML and you had 2 way for solving this
If you like markup languages you can use xsl that have if else tag for you
Using Javascript and check if you be on air show on air image and if you not be shows off air
for you the better way is change some javascript code in your site..
you should overwrite ohrdlog.LoadOnAir then you have two way again:
change http://www.hrdlog.net/hrdlog.js source code and rewrite LoadOnAir function
overwrite LoadOnAir function with inserting script tag after load http://www.hrdlog.net/hrdlog.js
i choose number 2 for you because i think you can`t change script that you load it from another domain address... now you should insert this code after this part:
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
and you can found link of offair image in HrdLog.prototype.ShowOffAir function that now, i point it to http://2.bp.blogspot.com/_Dr3YNV7OXvw/TGNNf561yQI/AAAAAAAABIk/-E2MB4jLP_o/s400/Off-Air.jpg:
<script type="text/javascript" language="javascript">
HrdLog.prototype.ShowOffAir = function() {
return '[<img src="https://i.stack.imgur.com/WEr1B.jpg" height="33" width="65" />][2]';
}
HrdLog.prototype.LoadOnAir = function() {
var t = this;
var async = new Async();
async.complete = function(status, statusText, responseText, responseXML, obj) {
if (status == 200) {
txt = '';
var xmldoc = responseXML;
var onairdoc = xmldoc.getElementsByTagName('OnAir');
if (onairdoc.length == 1) {
onair = onairdoc.item(0);
if (onair.getElementsByTagName('oa_QRZ').length > 0) {
txt += '<img src="http://www.hrdlog.net/images/onair.gif" height="33" width="65" /><br/>';
txt += '<font size="+1">' + onair.getElementsByTagName('oa_QRZ')[0].childNodes[0].nodeValue + ' is on air</font><br/>';
txt += '<b>';
txt += FormatNumber(onair.getElementsByTagName('oa_Frequency')[0].childNodes[0].nodeValue) + ' ';
try {
txt += onair.getElementsByTagName('oa_Mode')[0].childNodes[0].nodeValue + '</b><br/>';
txt += onair.getElementsByTagName('oa_Radio')[0].childNodes[0].nodeValue + '<br/><br/>';
} catch (e) { }
//txt += onair.getElementsByTagName('oa_Status')[0].childNodes[0].nodeValue + '<br/>';
}else{
txt += t.ShowOffAir();
}
}else{
txt += t.ShowOffAir();
}
element = document.getElementById('hrdlog-oa');
if (element != null) {
element.innerHTML = txt;
}
} else {
alert('Error\n' + statusText);
}
}
if ((new Date().getTime() - this._lastLoadOnAir.getTime()) > 14500) {
this._lastLoadOnAir = new Date();
async.req(this._host + 'hrdlog.aspx?onair=' + this._qrz, this);
}
}
</script>

Categories