I am trying to add a click event function to each name element in my function below for the autocomplete. When you click on the movie title, it should send that title through the getMovie and getQuotes function. However, the current code takes the last name in the autocomplete list and sends that title through, instead of the user click. I am not sure when the best solution is to the problem.
var sendTitle = function() {
var title = $("input[name='movie-search-title']").val();
getMovie(title)
getQuotes(title)
}
$("input[name='movie-search-title']").keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
sendTitle();
}
})
// movie autocomplete
var $input = document.getElementById('searchBox');
var baseUrl = "http://sg.media-imdb.com/suggests/";
var $result = document.getElementById('result');
$input.addEventListener('keyup', function() {
//clearing blank spaces from input
var cleanInput = $input.value.replace(/s/g, "");
//clearing result div if the input box in empty
if (cleanInput.length === 0) {
$result.innerHTML = "";
}
if (cleanInput.length > 0) {
var queryUrl = baseUrl + cleanInput[0].toLowerCase() + "/" +
cleanInput.toLowerCase() +
".json";
$.ajax({
url: queryUrl,
dataType: 'jsonp',
cache: true,
jsonp: false,
jsonpCallback: "imdb$" + cleanInput.toLowerCase()
}).done(function(result) {
//clearing result div if there is a valid response
if (result.d.length > 0) {
$result.innerHTML = "";
}
for (var i = 0; i < result.d.length; i++) {
var category = result.d[i].id.slice(0, 2);
if (category === "tt" || category === "nm") {
//row for risplaying one result
var resultRow = document.createElement('p');
resultRow.setAttribute('class', 'resultRow')
//creating and setting description
var description = document.createElement('div');
description.setAttribute('class', 'description');
var name = document.createElement('h4');
var snippet = document.createElement('h5');
if (category === "tt" && result.d[i].y) {
name.innerHTML = result.d[i].l + " (" + result.d[i].y + ")";
} else {
name.innerHTML = result.d[i].l;
}
snippet.innerHTML = result.d[i].s;
var nameText = name.innerHTML
$(description).append(name);
$(resultRow).append(description);
$("#result").append(resultRow);
}
// problem here!
$(name).click(function(e) {
e.preventDefault();
var title = nameText.slice(0, nameText.lastIndexOf(" "))
console.log(title)
getMovie(title)
});
}
});
}
});
// movie search
var getMovie = function(title) {
$("#main").removeClass("hidden");
$("#search-form").trigger("reset");
//format the OMDB api url
var apiUrl = `http://www.omdbapi.com/?t=${title}&plot=full&apikey=836f8b0`
//make a request to the url
fetch(apiUrl)
.then(function(response) {
// request was successful
if (response.ok) {
response.json().then(function(movieData) {
console.log(movieData)
showMovie(movieData)
});
} else {
alert("Error: title not found!");
}
})
.catch(function(error) {
alert("Unable to connect to cine score app");
});
};
var getMovieId = function(currMovieTitle) {
const settings = {
"async": true,
"crossDomain": true,
"url": `https://imdb8.p.rapidapi.com/title/find?q=${currMovieTitle}`,
"method": "GET",
"headers": {
"x-rapidapi-host": "imdb8.p.rapidapi.com",
"x-rapidapi-key": "229d984177msh18d191b1335378fp137dcejsn7c92ab2acfaf"
}
};
$.ajax(settings).done(function(response) {
console.log(response);
var specialId = response.results[0].id
var specialId = specialId.replace("/title/", "")
var specialId = specialId.replace("/", "")
console.log(specialId)
getSoundTrack(specialId)
});
}
var getSoundTrack = function(specialId) {
const settings = {
"async": true,
"crossDomain": true,
"url": `https://imdb8.p.rapidapi.com/title/get-sound-tracks?tconst=${specialId}`,
"method": "GET",
"headers": {
"x-rapidapi-host": "imdb8.p.rapidapi.com",
"x-rapidapi-key": "229d984177msh18d191b1335378fp137dcejsn7c92ab2acfaf"
}
};
$.ajax(settings).done(function(soundTrackData) {
console.log(soundTrackData);
});
}
var getQuotes = function(title) {
$("#quote-items").html("");
$("#movie-quotes-heading").removeClass("hidden");
var title = title.replaceAll(" ", "_")
const settings = {
"async": true,
"crossDomain": true,
"url": `https://movie-and-tv-shows-quotes.p.rapidapi.com/quotes/from/${title}`,
"method": "GET",
"headers": {
"x-rapidapi-host": "movie-and-tv-shows-quotes.p.rapidapi.com",
"x-rapidapi-key": "229d984177msh18d191b1335378fp137dcejsn7c92ab2acfaf"
}
};
$.ajax(settings).done(function(quoteData) {
console.log(quoteData);
showQuotes(quoteData)
})
.fail(function(xhr, status, error) {
//Ajax request failed.
var errorMessage = xhr.status + ': ' + xhr.statusText
console.log(`Error - ${errorMessage}`);
$("#movie-quotes-heading").addClass("hidden");
});
}
var showMovie = function(movieData) {
$("#movie-title").text(movieData.Title)
let currMovieTitle = movieData.Title
getMovieId(currMovieTitle);
$("#year-rating").text(`${movieData.Year}, ${movieData.Rated}`)
$("#genre").text(`${movieData.Genre}`)
$("#synopsis").text(movieData.Plot)
$("#poster").attr("src", movieData.Poster);
$("#cast-list").text(`Main Cast: ${movieData.Actors}`)
$("#director").text(`Director: ${movieData.Director}`)
$("#writer").text(`Writer(s): ${movieData.Writer}`)
$("#imdb-rate").text(`${movieData.Ratings[0].Source} - ${movieData.Ratings[0].Value}`)
$("#tomatoes-rate").text(`${movieData.Ratings[1].Source} - ${movieData.Ratings[1].Value}`)
$("#metacritic-rate").text(`${movieData.Ratings[2].Source} - ${movieData.Ratings[2].Value}`)
var tomatoesRate = (movieData.Ratings[1].Value).replace("%", "")
parseInt(tomatoesRate)
if (tomatoesRate <= 60) {
$("#tomatoes-rate").attr("src", "https://www.clipartmax.com/png/full/351-3516739_cherry-tomato-clipart-tomatoe-rotten-tomatoes-icon-png.png")
} else if (tomatoesRate >= 60) {
$("#tomatoes-rate").attr("src", "https://www.clipartmax.com/png/full/50-503981_rotten-tomatoes-fresh-logo.png")
}
}
var showQuotes = function(quoteData) {
$("#movie-quotes-heading").text("Movie Quotes")
quoteData.forEach(quoteItem => {
var carouselItem = document.createElement("div")
$(carouselItem).html(`<h4 class='quote'>"${quoteItem.quote}"<br><br><span class='quote-character'>-${quoteItem.character}</span></h4><br>`)
$(carouselItem).appendTo("#quote-items");
});
}
body {
font: 400 15px Lato, sans-serif;
line-height: 1.8;
color: #818181;
}
.hidden {
display: none;
}
h2 {
font-size: 24px;
text-transform: uppercase;
color: #303030;
font-weight: 600;
margin-bottom: 30px;
}
h4 {
font-size: 19px;
line-height: 1.375em;
color: #303030;
font-weight: 400;
margin-bottom: 30px;
}
.jumbotron {
background-color: #40376E;
color: #fff;
padding: 100px 25px;
font-family: Montserrat, sans-serif;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
form {
width: 100%;
display: flex;
gap: 20px;
flex-direction: row;
}
#results {
display: flex;
flex-direction: column;
justify-content: left;
width: 20%;
text-align: left;
color: antiquewhite;
}
.container-fluid {
padding: 60px 50px;
}
.bg-grey {
background-color: #f6f6f6;
}
.logo-small {
color: #40376E;
font-size: 50px;
}
.logo {
color: #40376E;
font-size: 200px;
}
.thumbnail {
padding: 0 0 15px 0;
border: none;
border-radius: 0;
}
.thumbnail img {
width: 100%;
height: 100%;
margin-bottom: 10px;
}
#tomatoes-rate {
width: 80%;
height: 80%;
}
.carousel-control.right,
.carousel-control.left {
background-image: none;
color: #40376E;
}
.carousel-indicators li {
border-color: #40376E;
}
.carousel-indicators li.active {
background-color: #40376E;
}
.item h4 {
font-size: 19px;
line-height: 1.375em;
font-weight: 400;
font-style: italic;
margin: 70px 0;
}
.item span {
font-style: normal;
}
.panel {
border: 1px solid #40376E;
border-radius: 0 !important;
transition: box-shadow 0.5s;
}
.panel:hover {
box-shadow: 5px 0px 40px rgba(0, 0, 0, .2);
}
.panel-footer .btn:hover {
border: 1px solid #40376E;
background-color: #fff !important;
color: #40376E;
}
.panel-heading {
color: #fff !important;
background-color: #40376E !important;
padding: 25px;
border-bottom: 1px solid transparent;
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;
}
.panel-footer {
background-color: white !important;
}
.panel-footer h3 {
font-size: 32px;
}
.panel-footer h4 {
color: #aaa;
font-size: 14px;
}
.panel-footer .btn {
margin: 15px 0;
background-color: #40376E;
color: #fff;
}
.navbar {
margin-bottom: 0;
background-color: #40376E;
z-index: 9999;
border: 0;
font-size: 12px !important;
line-height: 1.42857143 !important;
letter-spacing: 4px;
border-radius: 0;
font-family: Montserrat, sans-serif;
}
.navbar li a,
.navbar .navbar-brand {
color: #fff !important;
}
.navbar-nav li a:hover,
.navbar-nav li.active a {
color: #40376E !important;
background-color: #fff !important;
}
.navbar-default .navbar-toggle {
border-color: transparent;
color: #fff !important;
}
footer .glyphicon {
font-size: 20px;
margin-bottom: 20px;
color: #40376E;
}
.slideanim {
visibility: hidden;
}
.slide {
animation-name: slide;
-webkit-animation-name: slide;
animation-duration: 1s;
-webkit-animation-duration: 1s;
visibility: visible;
}
@keyframes slide {
0% {
opacity: 0;
transform: translateY(70%);
}
100% {
opacity: 1;
transform: translateY(0%);
}
}
@-webkit-keyframes slide {
0% {
opacity: 0;
-webkit-transform: translateY(70%);
}
100% {
opacity: 1;
-webkit-transform: translateY(0%);
}
}
@media screen and (max-width: 768px) {
.col-sm-4 {
text-align: center;
margin: 25px 0;
}
.btn-lg {
width: 100%;
margin-bottom: 35px;
}
}
@media screen and (max-width: 480px) {
.logo {
font-size: 150px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cine Score</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="assets/css/style.css" </head>
<body id="mainPage" data-spy="scroll" data-target=".navbar" data-offset="60">
<!-- Navigation Menu -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#myPage">Cine Score</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li><a href="#past-searches">Past Searches</a></li>
<li><a href="#favorite-soundtracks">Favorite Soundtracks</a></li>
</ul>
</div>
</div>
</nav>
<!-- Movie Search Jumbotron -->
<div id="movie-search" class="jumbotron text-center">
<h1>Search for a movie!</h1>
<form id="search-form">
<input id="searchBox" name="movie-search-title" type="text" class="form-control" size="50" placeholder="movie title" />
<button id="searchBtn" type='button' class="btn btn-danger" onclick="sendTitle()">Search</button>
</form>
<div id="result"></div>
</div>
<main id="main" class=hidden>
<!-- Container (main movie info) -->
<div id="movie-info" class="container-fluid">
<div class="row">
<div class="col-sm-8">
<h2 id="movie-title"></h2><br>
<h4 id="year-rating"></h4>
<h4 id="genre"></h4><br>
<p id="synopsis"></p>
<br><button id="get-soundtrack" class="btn btn-default btn-lg">Get the soundtrack</button>
</div>
<div class="col-sm-4">
<span id="movie-poster">
<img id="poster" src="" />
</span>
</div>
</div>
</div>
<!-- Container (cast) -->
<div id="cast" class="container-fluid bg-grey">
<div class="row">
<div id="cast-icon" class="col-sm-4">
<span>
<img src="https://cdn-icons-png.flaticon.com/512/3873/3873990.png" />
</span>
</div>
<div class="col-sm-8">
<h2>Cast</h2><br>
<h4 id="cast-list"></h4><br>
<p id="director">
</p>
<p id="writer">
</p>
</div>
</div>
</div>
<!-- Container (Score Section) -->
<div id="score" class="container-fluid">
<div class="row">
<div class="col-sm-4">
<span id="rating-img">
<img id="tomatoes-rate" src=""/>
</span>
</div>
<div class="col-sm-8 text-center">
<h2>SCORE</h2><br>
<h4 id="imdb-rate"></h4><br>
<h4 id="tomatoes-rate"></h4><br>
<h4 id="metacritic-rate"></h4><br>
</div>
</div>
</div>
<!-- Container (Sountrack Section) -->
<div id="soundtrack" class="container-fluid text-center bg-grey">
<h2>Sountrack</h2><br>
<h4 id="movie-title-soundtrack">Movie Soundtrack</h4>
<div class="container-fluid text-center">
<p>Soundtrack Image</p>
<p>List of songs</p>
<button id="save-to-favorites" class="btn btn-default btn-lg">Save to favorites!</button>
</div>
</div>
<!-- Container (Movie Quotes Section)-->
<div id="movie-quotes" class="container-fluid text-center">
<h2 id="movie-quotes-heading"></h2>
<div id="quote-items" class="carousel slide text-center" data-ride="carousel"></div>
</div>
<!-- Footer -->
<footer class="container-fluid text-center">
<a href="#mainPage" title="To Top">
<span class="glyphicon glyphicon-chevron-up"> Top </span>
</a>
</footer>
</main>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="assets/js/script.js"></script>
</html>