Javascript issue. Receive object HTMLinputelement error - javascript

I was trying to copy RSS feed from Reddit site, and use below code, but received HTMLInputElement error. I am not sure if my var function is correct to get content. Please help. Thank you!
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Get Reddit Keyword RSS Feed</h1>
<input id="keyword" placeholder="Reddit Keyword">
<button id="submit">Get Reddit RSS Feed</button>
<script type="text/javascript">
$('#submit').click(function() {
if ($('#keyword').val() != '') {
alert('For demonstration purposes only. Please do not point your RSS reader to this server.');
var keyword = $('#keyword').val();
$('#output').html('').append('http://www.reddit.com/r/' + $('#keyword').val()) '/.rss').attr('href', 'http://www.reddit.com/r/' + $('#keyword').val()) '/.rss');
}
});
</script>
</body>
</html>

I think issue is with your code,
at line
$('#output').html('').append('http://www.reddit.com/r/' + $('#keyword').val()) '/.rss').attr('href', 'http://www.reddit.com/r/' + $('#keyword').val()) '/.rss');
There is syntax error, brackets are not getting closed at right places.
$('#output').html('')
.append('http://www.reddit.com/r/' + $('#keyword').val()+ '/.rss')
.attr('href', 'http://www.reddit.com/r/' + $('#keyword').val() + '/.rss');

Related

How to Change Background Image Based on User Input | HTML, CSS, JS

I have done a lot of research on how to do this, yet I can't seem to find a specific answer. I am trying to allow the user to input a file from their computer, and turn that file into the background of the webpage. My following code is shown below:
<head>
<script>
function changeBackground() {
var input = document.getElementById("background").value;
localStorage.setItem("Background", input);
var result = localStorage.getItem("Background");
$('body').css({ 'background-image': "url(" + result + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>
If someone could please explain to me what I need to do to get this to work, I would very much appreciate it. I already understand I need to use localStorage to make sure that the selected background is remembered, I am just having trouble getting the background to change. If there is already an article on how to do this, I would appreciate a link to it. Thanks!
EDIT
Nikhil and user6003859 explained to me why it isn't working. I guess I just need to figure out how to use Ajax and PHP to change it. If anyone has more advice on this, I would love to hear it. Thanks everyone for helping me solve this problem.
Modern browsers normally restrict access to the user's local files (in this case an image). What you're trying to do is display an image from the user's local filestorage, via the path you get from the <input type='file' /> value.
What you should instead be doing, is uploading the image to your server (probably with ajax, so it feels seamless), and then displaying the file from your server on to your page.
EDIT: Even though this is kind of a new question, I'll give you an example on how to change an element's background based on a URL provided by the user:
var inp = document.getElementById('inp');
var res = document.getElementById('res');
inp.oninput = function()
{
res.style.backgroundImage = 'url(' + inp.value + ')';
};
div
{
width: 5em;
height: 5em;
}
<input type='text' id='inp' />
<div id='res'>
</div>
It's better practice to use file reader.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#file").change(function(){
var length=this.files.length;
if(!length){
return false;
}
changeBackground(this);
});
});
// Creating the function
function changeBackground(img){
var file = img.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
alert("Invalid File Extension");
}else{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(img.files[0]);
}
function imageIsLoaded(e) {
$('body').css({ 'background-image': "url(" + e.target.result + ")" });
}
}
</script>
</head>
<body>
<input type="file" name="" id="file" value="Click">
</body>
</html>
You cannot do that purely with client-side because of security reasons.
The moment you upload say an image, the browser gives it a "fakepath" like so:
C:\fakepath\<filename>.png
This is a security implementation of the browser - the browser is protecting you from accessing your disk structure.
Hence when you check the value of your input after uploading, you would get the above fakepath ie. C:\fakepath\<filename>.png. Using this as the background obviously would not work.
Usually to achieve this you need to first store it in a server, then fetch the value from the server and apply the background.
To use a local file, store it in a blob
<head>
<script>
function changeBackground() {
var backgroundFile = document.getElementById("background").files[0];
$('body').css({ 'background-image': "url(" + URL.createObjectURL(backgroundFile) + ")" });
}
</script>
</head>
<body>
<input id="background" type="file" onchange="changeBackground()">
</body>

YouTube Data API v3 Using Javascript

I am kind of new to writing code and using API's. I am not entirely sure why my program is not working the way I would like it to.
What I want this to do is provide the search results in the console before I can move onto what I would like it to do next; however, I don't think anything is being searched.
According to this: https://developers.google.com/youtube/v3/docs/search/list#http-request, the only required parameter is "part," so I think I did everything right? Probably not though, because from what I can tell, nothing is being searched when I try to search for a term.
Here is my code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<section>
<form id="search-term">
<p>Enter Name:<br/>
<input id="query" type="text" name="Name"/><br/>
<hr/>
<input type="button" value="Enter here"/>
</p>
<div id="search-results">
</div>
</form>
</section>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
JavaScript:
$(document).ready(function(){
$('#search-term').submit(function(event){
event.preventDefault();
var searchTerm = $('#query').val();
getRequest(searchTerm);
});
function getRequest(searchTerm){
var params = {
"q": "searchTerm",
"part": 'snippet',
"type": 'video',
"key": 'I was advised to keep my key private, so I edited this part out'
}
url = 'https://www.googleapis.com/youtube/v3/search';
$.getJSON(url, params, function(data){
showResults(data.items);
})
}
function showResults(results){
var html = "";
$.each(results, function(index,value){
html += '<p>' + value.snippet.thumbnails.high.url + '</p>' + '<p>' + 'https://www.youtube.com/watch?v=' + value.id.videoId + '</p>' + '<hr/>';
console.log(value.snippet.thumbnails.high.url);
console.log(value);
})
$('#search-results').html(html);
}
})
You probably want data.items instead of data.search
I don't see any mention of a 'search' parameter under the "Response" section listed in their documentation. See the response properties here: https://developers.google.com/youtube/v3/docs/search/list#response
Therefore, you can probably see some output if you console.log(data); instead of data.search
I recommend you check out Google's Javascript API Client Library. It might not be the best solution for you, but it's worth a try. Download on GitHub
Example using gapi.client.youtube.search.list:
// After the API loads, call a function to enable the search box.
function handleAPILoaded() {
$('#search-button').attr('disabled', false);
}
// Search for a specified string.
function search() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}

Jquery/Ajax - Get Picture and Youtube in HTML

So i'm back here again trying to figure out how to use HTML correct and can't get it to work correctly after been trying many hours with this.
Anyways, i'm trying to make so the picture and youtube trailer should be shown in the HTML and what I search for is something like this.
Right now im searching to make something like the picture but to get picture to be shown and a player with the trailer
so basically I want it to look similar like picture number one and I have come so far:
<!DOCTYPE html>
<html>
<head>
<title>Movies</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function callAjax(input)
{
var url = "http://localhost:1337/search/" + input;
$.ajax({
type:'GET',
url: url,
success: function(data)
{
console.log('SUCCESS');
$('#title').html("Title: " + data.title);
$('#release').html("Release: " + data.release);
$('#vote').html("Vote: " + data.vote);
$('#overview').html("Overview: " + data.overview);
$('#poster').html("Poster: " + data.poster);
},
error: function(request, status, err)
{
console.log('ERROR');
}
});
}
$(document).ready(function(){
$('#get-json').on('click', function(e){
e.preventDefault();
var input = $('#data').val().trim();
callAjax(input);
});
});
</script>
<body>
<center>
<div>
<input type="text" id="data" name="data" size="15" maxlength="120" />
<button type="submit" value="search" id="get-json">Search</button>
</div>
</center>
<section>
<div id="json-output"></div>
<div id="title"></div>
<div id="release"></div>
<div id="vote"></div>
<div id="overview"></div>
<div id="poster" img src="data.poster" style="width:104px;height:142px;"></div>
</section>
</body>
</html>
Also forgot to say that i'm very new at this, never done HTML really before and been trying to figure out this for a while without a result :(
You need to create placeholders for your JSON elements. At first write without that JSON a sample of HTML page that will look like you want. That page should have elements (for example div) for title, release and so on. Those elements should have its class or ids to be addressed (as it is already with <div id="json-output">)
You do not have to stringify your JSON. It is better to work JSON, since you can address its elements. For example, to set value into specific placeholder element you can use:
$('#title').html(data.title);
$('#relese').html(data.release);
$('#vote').html(data.vote);
JSON.stringify will return the contents of a JSON object as a string. It will not parse your JSON object and return HTML.
You can create a simple list like this:
function(data){
var $list = $('<ul>');
$list.append('<li>Title: ' + data.title + '</li>');
$list.append('<li>Release: ' + data.release + '</li>');
$list.append('<li>Vote: ' + data.vote + '</li>');
$list.append('<li>Overview: ' + data.overview + '</li>');
$('#json-output').html($list);
}

Debugging jquery or javascript using firebug

I wrote a code in jquery. I was not running initially, then i checked online jslint for syntax errors. I caught some errors. Now still the code was not working as expected. So i went for firebug. I haven't done a lot of debugging. I am new to it. Here is my code
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
console.log("button clicked");
var a =[];
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
var rows = response.rows;
alert("hello there");
for (var i = 0; i < rows.length; i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = rows[i].elements[j].distance;
}
}
alert(distance[1][3]);
});
});
});
Now, what it should do is Go to this link and get the data from json file and store it inside the 2 dimensional array distance[][]. Finally after storing all the data, it should display the result of "distance[1][2]" as an alert.
Now i dont know whats wrong in this code and how to find the logical errors using firebug. What should make my work easy ?
ps: heres the HTML file
<!doctype html>
<html>
<head>
<title>TakeMeHome</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/jquery-1.9.0.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.0.custom.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.0.custom.min.js"></script>
</head>
<body>
<center>
<form id="locations">
Your Place:<input id="source" type="text"><br/>
<br/>
<div id="friends">
Friend1:<input id="friend1" type="text"><br/>
<br/>
</div>
<div id="button">
Add!</div>
<br/>
<br/>
<button>GO!</button>
<br/><br/>
<div id="map" style = "width: 500px; height: 500px"><br/>
</form>
</center>
</body>
</html>
Hey here is a working fiddle with your code, and some examples of ways to debug your js :
http://jsfiddle.net/QxP7p/3/
As you see you can do nice stuff like :
console.log("distance : ");
console.log(distance);
Hope it helps
They were a few mistakes as well, couldn't help fixing them
The easiest way to debug is to use firebug and console.log() variables or messages at certain points in your script, so that you can better understand what is going on at various steps of your script. You can see the output in the Console tab of firebug.
You can also add breakpoints and watches from some of the other tabs. For example in the DOM tab you can rightclick on a variable and add a watch, or from the Script tab you can click on a position in your script to set a breakpoint or watch, and it will stop the script at that point and/or show a dump of vars at that point.

populating div from external file div with javascript and jquery

Very frustrated here. Can't get this to work and don't know why.
I am trying to populate my div with a div from another html file. Here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="text">
content goes here
</div>
<script type="text/javascript">
function whenButtonClicked() {
var book = document.getElementById("book").value; //this is working
var chapter = document.getElementById("chapter").value; //this is working
var filename = 'files/' + book + chapter + '.html'; //this is working
$('#text').load(filename #source); //this is NOT
}
</script>
Thanks for any help.
Adam
Edit: Here is a link to the actual file I am working on. There may be something wrong in it as well.
Use this code: $('#text').load(filename + " #source");.

Categories

Resources