How to select data from DIV's with something like $this? - javascript

given the following code snippet:
<div class="container-fluid" id="networdapp">
<div class="row" >
<div v-for="result in results" class="col-sm-6" >
<div class="card m-3 h-240 bg-light">
<div class="card-header text-center"> {{ result.title }} </div>
<div class="card-body" style="height:200px" >
<p class="card-text" v-html="result.prevDesc"></p>
</div>
<div class="card-footer bg-transparent border-info">
Details
</div>
</div>
</div>
</div>
</div>
How can I read data from a random div/unknown position in for div? I can't use PHP.
This <div ... id="networdapp"> is created depending on the results from a database. How can I get the data {{result.title}} from a random div when I click the "Details" button from it?
I tried to get it using JQuery but I ended up by selecting all data from all DIVs. Then I was thinking if I can do that with $this and I tried but still can't do it.
EDIT: There is the generated html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Website Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">WebSite for testing</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarWw1" aria-controls="navbarWw1" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarWw1">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="map">Map</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about">About</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="myInput" type="search" onkeyup="myFunction()" placeholder="Find your next memories!">
</form>
</div>
</nav>
<div class="container-fluid" id="networdapp" style="display:none;">
<div class="row" >
<div v-for="result in results" class="col-sm-6" >
<div class="card m-3 h-240 bg-light" >
<div class="card-header text-center" > {{ result.title }} </div>
<div class="card-body" style="height:200px" >
<p class="card-text" v-html="result.prevDesc"></p>
</div>
<div class="card-footer bg-transparent border-info">
<a href="/details" class="btn btn-info" >Details</a>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function myFunction() {
var input , filter , OK = false ;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
if(filter.length > 0 ) {
document.getElementById("networdapp").style.display = "";
$( ".col-sm-6" ).each(function( index ) {
if ($(this).text().toUpperCase().indexOf(filter) > -1){
this.style.display="";
}else{
this.style.display="none";
//document.getElementById("networdapp").style.display = "none";
}
});
}
else{
document.getElementById("networdapp").style.display = "none";
}
}
</script>
<script type="text/javascript">
const vm = new Vue({
el: '#networdapp',
data: {
results:[]
},
mounted() {
axios.get('/getJson')
.then(response => {
this.results = response.data;
})
.catch( e => {
console.log(e);
});
}
});
</script>
</html>

The div has the class card-header, so...
$('.card-header').text()
//or
document.getElementsByClassName('card-header')[0].innerText
//or
document.querySelector('.card-header').innerText
//or
document.querySelectorAll('.card-header')[0].innerText
However, you want to get the one related to the button clicked. So that could look something like...
//create a delegate event handler on the container for all the buttons
$('#networdapp').on('click', '.btn.btn-info', function (e) {
//prevent the link so the runnable snippet stops jumping back to the top
e.preventDefault();
//find the parent div with the card class that is the parent to both
//the link and the title
var $card = $(this).closest('.card');
//find the nested card header in the card clicked
var $cardHeader = $card.find('.card-header');
//console log the text
console.log($cardHeader.text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid" id="networdapp">
<div class="row">
<div v-for="result in results" class="col-sm-6" >
<div class="card m-3 h-240 bg-light">
<div class="card-header text-center"> title 1 </div>
<div class="card-body" style="height:200px" >
<p class="card-text" v-html="result.prevDesc"></p>
</div>
<div class="card-footer bg-transparent border-info">
Details
</div>
</div>
</div>
</div>
<div class="row">
<div v-for="result in results" class="col-sm-6" >
<div class="card m-3 h-240 bg-light">
<div class="card-header text-center"> title 2 </div>
<div class="card-body" style="height:200px" >
<p class="card-text" v-html="result.prevDesc"></p>
</div>
<div class="card-footer bg-transparent border-info">
Details
</div>
</div>
</div>
</div>
<div class="row">
<div v-for="result in results" class="col-sm-6" >
<div class="card m-3 h-240 bg-light">
<div class="card-header text-center"> title 3 </div>
<div class="card-body" style="height:200px" >
<p class="card-text" v-html="result.prevDesc"></p>
</div>
<div class="card-footer bg-transparent border-info">
Details
</div>
</div>
</div>
</div>
</div>

Using jQuery:
$("#networdapp .card-header.text-center").html()
So:
$(".btn.btn-info").click(function(){
console.log( $("#networdapp .card-header.text-center").html() );
})
Or:
$(".btn.btn-info").click(function(){
console.log( $(this).closest("#networdapp").find(".card-header.text-center").html() );
})

You can select div then use the context to select the button r other elements within.
$(".card").each(function(){
var that = this; // <--- the current div
var header = $(that).find(".card-header");
var detailBtn = $(that).find(".btn-info");
// set event handlers here
// Example:
detailBtn.click(function(){
alert(header.text());
});
});
Here is a working Example

Using jquery
$(this).parents("#networdapp").find(".card-header.text-center").text();
To remove unneccesay spaces you can use trim
$.trim($(this).parents("#networdapp").find(".card-header.text-center").text());

Related

Bootstrap5 tab content on second tab creates unlimited white space

in my project I want to show statistics for the current month and the current year. To split this statistics I created a card with tabs that split month and year.
The month tab is loaded as default. If i now go on the year tab everything is loading but then it will load unlimited empty "stuff / white data" (I don't know how to explain it better), and you can't use this tab because the site will be bigger and bigger. There is also no error in the
This has first been poped up after I changed alle my charts (chart.js) to an dynamic way that you can go e.g. to the next month or the month before. If I load all charts with "fixed" data then the tab works correctly.
What is the problem?
Actual look:
How it has to be looked:
After some testing i see this:
Code snippet:
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.2/dist/umd/popper.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-header">
<div>
<ul class="nav nav-pills nav-fill mt-4" role="tablist">
<li class="nav-item active">
<a class="nav-link" data-bs-toggle="tab" href="#Month" role="tab">
<span><strong>Current Month</strong></span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" data-bs-toggle="tab" href="#Year" role="tab">
<span><strong>Current Year</strong></span>
</a>
</li>
</ul>
</div>
</div>
<div class="card-body">
<div class="tab-content">
<div class="tab-pane active" id="Month" role="tabpanel">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="card-header d-flex justify-content-between align-items-center">
<h2 class="card-title" id="month"></h2>
<div class="justify-content-end">
<button class="btn btn-info last-month" id="last-month"><i class="fas fa-chevron-left"></i></button>
<button class="btn btn-info current-month" id="current-month">Current Month</button>
<button class="btn btn-info next-month" id="next-month"><i class="fas fa-chevron-right"></i></button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header bg-inverse">
<h2 class="card-title text-white" id="monthly_training_sessions"></h2>
</div>
<div class="card-body">
<span class="badge chart-label-intervall">Intervall</span>
<span class="badge chart-label-longrun">Longrun</span>
<span class="badge chart-label-speedwork">Speedwork</span>
<span class="badge chart-label-stabilisation">Stabilisation</span>
<span class="badge chart-label-competition">Competition</span>
<span class="badge chart-label-cycling">Cycling</span>
<span class="badge chart-label-swimming">Swimming</span>
<br><br>
<canvas id="monthy_session_stats" width="180" height="180"></canvas>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header bg-inverse d-flex justify-content-between">
<h2 class="card-title text-white" id="monthly_training_days"></h2>
<h2 class="card-title text-white" id="monthly_injury_days"></h2>
</div>
<div class="card-body">
<div class="d-flex justify-content-evenly" style="margin-bottom: 18px">
<span class="badge chart-label-training">Training</span>
<span class="badge chart-label-injury">Free</span>
<span class="badge chart-label-free">Injury</span>
</div>
<br>
<canvas id="monthy_training_stats" width="180" height="180"></canvas>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header bg-inverse">
<h2 class="card-title text-white">Shoes</h2>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<tbody id="monthly_shoes_stats">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="Year" role="tabpanel">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="card-header d-flex justify-content-between align-items-center">
<h2 class="card-title" id="year"></h2>
<div class="justify-content-end">
<button class="btn btn-info last-year" id="last-year"><i class="fas fa-chevron-left"></i></button>
<button class="btn btn-info current-year" id="current-year">Current Year</button>
<button class="btn btn-info next-year" id="next-year"><i class="fas fa-chevron-right"></i></button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header bg-inverse">
<h2 class="card-title text-white" id="yearly_training_sessions"></h2>
</div>
<div class="card-body">
<span class="badge chart-label-intervall">Intervall</span>
<span class="badge chart-label-longrun">Longrun</span>
<span class="badge chart-label-speedwork">Speedwork</span>
<span class="badge chart-label-stabilisation">Stabilisation</span>
<span class="badge chart-label-competition">Competition</span>
<span class="badge chart-label-cycling">Cycling</span>
<span class="badge chart-label-swimming">Swimming</span>
<br><br>
<canvas id="yearly_session_stats" width="180" height="180"></canvas>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header bg-inverse d-flex justify-content-between">
<h2 class="card-title text-white" id="yearly_training_days"></h2>
<h2 class="card-title text-white" id="yearly_injury_days"></h2>
</div>
<div class="card-body">
<div class="d-flex justify-content-evenly" style="margin-bottom: 18px">
<span class="badge chart-label-training">Training</span>
<span class="badge chart-label-injury">Free</span>
<span class="badge chart-label-free">Injury</span>
</div>
<br>
<canvas id="yearly_training_stats" width="180" height="180"></canvas>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header bg-inverse">
<h2 class="card-title text-white">Shoes</h2>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<tbody id="yearly_shoes_stats">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
After a lot of researching and reading i found the solution for this problem.
The problem occurs because of the hidden content from the hidden tab, which is realized in Bootstrap via "display: none".
.tab-content > .tab-pane, .pill-content > .pill-pane {
display: none; /* this is the problem */
}
To fix this problem you can use height: 0 and overflow-y: hidden to this . Now the charts will stay in place and no empty random space will created.
.tab-content > .tab-pane:not(.active),
.pill-content > .pill-pane:not(.active) {
display: block;
height: 0;
overflow-y: hidden;
}
It will take a little minute to go through that line by line but some of the problem is sure to be your structure of Rows and Columns. I noticed this in the first few lines - Just inside the tab-content is this...
<div class="tab-pane active" id="Month" role="tabpanel">
<div class="row">
<div class="col-md-12">
<div class="row">
With Bootstrap you're not really meant to have the Row's inside the Column's and I think what's happening is that the un-natural layout of the code is creating errors like the one you see. This answer does not discover where your white-space is coming from but I do suspect that fixing the layout of the code will also fix the white-space.

javascript script no working adding classlist to an element

i am trying to make a quiz app with javascript but it does not work i want when i click on one of the option if it is the first option i wanna set its class to correct and the others to in-correct but it does not work for me i do not know where is the problem or what i did wrong , ...
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="./../images/quizapp.png" type="image" >
<link rel="stylesheet" href="./../css/bootstrap.min.css">
<link rel="stylesheet" href="./../css/default.css">
<link rel="stylesheet" href="./../css/quizap.css">
<title>Document</title>
<header class="container p-4 text-center border">
<h1 class="h1 text-danger">Quiz Application With JavaScript</h1>
</header>
<div class="container landing p-5 mt-3 text-center">
<div class="description m-auto">
<h2 class="h2 border text-center p-3">Welcome To The Quiz App...</h2>
</div>
<div class="collection container" id="categorie">
<div class="row mt-5 container">
<div class="col-4 categories text-center" id="sports">
Sports
</div>
<div class="col-4 categories text-center" id="music">
Music
</div>
<div class="col-4 categories text-center" id="food" >
General
</div>
</div>
</div>
<div class="question" id="sports_question">
<div class="list_questions list-group" id="answers">
<li class="list-group-item">
<h3 class="h3">
<div id="firstQuestion" class="container q_container">
<div class="card my-card">
<div class="card-body ">
<h5 class="card-title">Who Is My Favorite FootBall Team?</h5>
<p class="card-text options">
<div class="option_one option" value="1">Wydad</div>
<div class="option_two option" value="0">Raja</div>
<div class="option_thre option" value="0">Mat</div>
<div class="option_frour option" value="0">Fus</div>
</p>
</div>
</div>
</div>
</h3>
</li>
<li class="list-group-item">
<h3 class="h3">
<div id="firstQuestion" class="container q_container">
<div class="card my-card">
<div class="card-body ">
<h5 class="card-title">Who Is My Favorite FootBall Team?</h5>
<p class="card-text options">
<div class="option_one option">Wydad</div>
<div class="option_two option">Raja</div>
<div class="option_thre option">Mat</div>
<div class="option_frour option">Fus</div>
</p>
</div>
</div>
</div>
</h3>
</li>
<li class="list-group-item">
<h3 class="h3">
<div id="firstQuestion" class="container q_container">
<div class="card my-card">
<div class="card-body ">
<h5 class="card-title">Who Is My Favorite FootBall Team?</h5>
<p class="card-text options">
<div class="option_one option">Wydad</div>
<div class="option_two option">Raja</div>
<div class="option_thre option">Mat</div>
<div class="option_frour option">Fus</div>
</p>
</div>
</div>
</div>
</h3>
</li>
<li class="list-group-item">
<h3 class="h3">
<div id="firstQuestion" class="container q_container">
<div class="card my-card">
<div class="card-body ">
<h5 class="card-title">Who Is My Favorite FootBall Team?</h5>
<p class="card-text options">
<div class="option_one option">Wydad</div>
<div class="option_two option">Raja</div>
<div class="option_thre option">Mat</div>
<div class="option_frour option">Fus</div>
</p>
</div>
</div>
</div>
</h3>
</li>
<li class="list-group-item">
<h3 class="h3">
<div id="firstQuestion" class="container q_container">
<div class="card my-card">
<div class="card-body ">
<h5 class="card-title">Who Is My Favorite FootBall Team?</h5>
<p class="card-text options">
<div class="option_one option">Wydad</div>
<div class="option_two option">Raja</div>
<div class="option_thre option">Mat</div>
<div class="option_frour option">Fus</div>
</p>
</div>
</div>
</div>
</h3>
</li>
</div>
</div>
</div>
<script src="./../script/popper.min.js"></script>
<script src="./../script/bootstrap.min.js"></script>
<script src="./../script/quizap.js"></script>
and this is the javascript code:
let categories = document.querySelectorAll('.categories');
let sports_question = document.getElementById('sports_question');
let collection = document.getElementById('categorie');
let options = document.querySelectorAll('.list_questions');
let elements = document.querySelectorAll('.question');
for (let i = 0; i < options.length; i++) {
options[i].addEventListener('click', function (e) {
const selectedOption = e.target;
console.log(selectedOption);
const correct = selectedOption.dataset.correct;
Array.from(options[i].children).forEach(option => {
SetStatus(option, option.dataset.correct);
console.log(option.dataset.correct + 'this is the option');
});
})
}
function SetStatus(option, correct) {
if (correct) {
option.classList.add('correct');
} else {
option.classList.add('in-correct');
}
}
for (let i = 0; i < categories.length; i++) {
categories[i].addEventListener('click', function () {
sports_question.classList.toggle('active');
collection.classList.toggle('hide');
})
}
querySelector all returns nodeList not array of elements.
use spread operator to convert them to array.
here's an example
let options = [...document.querySelectorAll('.list_questions')];
First
The div tag can NOT be inside p tag, because the paragraph will be broken at the point, where the div tag is entered.
So change p and div into ul and li
HTML
<ul class="card-text options">
<li class="option_one option" value="1">Wydad</li>
<li class="option_two option" value="0">Raja</li>
<li class="option_thre option" value="0">Mat</li>
<li class="option_frour option" value="0">Fus</li>
</ul>
JavaScript
const options = document.querySelectorAll(".option");
(function addEventListeners() {
options.forEach((option) => {
option.addEventListener("click", (event) => {
const { parentNode } = event.target;
setClasses(parentNode, option);
});
});
})();
function setClasses({ children }, selected) {
[...children].forEach((child) => {
if (child !== selected) {
child.classList.add("in-correct");
child.classList.remove("correct");
return;
}
child.classList.remove("in-correct");
child.classList.add("correct");
});
}

How can I access the value of a specific button that has the same classes

I am developing a web app of where the user can search the song lyrics they want. I am using an API for it. Now I can generate 10 songs results, but the problem is when a user click on "get lyrics" button I can not access the value of that specific button's song title. How can I get the specific song title and album name by just clicking the get lyrics button? Here is my final result:
const apiUrl = "https://api.lyrics.ovh/suggest";
const search = document.getElementById("search-btn");
const result = document.getElementById("result");
const text = document.getElementById("text");
const getLyrics = document.getElementsByClassName("get-lyrics");
//search by songs or artist...
function searchSongs(term) {
fetch (`${apiUrl}/${term}`)
.then (response => response.json())
.then (data => {
const lyricsName = document.getElementsByClassName("lyrics-name");
for (let index = 0; index < lyricsName.length; index++) {
const element = lyricsName[index];
element.innerText = data.data[index].album.title;
}
const artist = document.getElementsByClassName("artist");
for (let index = 0; index < artist.length; index++) {
const element = artist[index];
element.innerText = data.data[index].artist.name;
}
document.getElementById("result").style.display = "block";
//console.log(data);
});
}
//event listener to search song or artist
search.addEventListener("click", e => {
//e.preventDefault();
const searchTerm = text.value;
if (!searchTerm) {
alert("please type a song a name");
} else {
searchSongs(searchTerm);
}
})
//event listener to get lyrics
for (let index = 0; index < getLyrics.length; index++) {
const element = getLyrics[index];
element.addEventListener("click", function(){
const title = `${index + 1}`;
})
}
<!doctype html>
<html lang="en">
<head>
<title>Hard Rock Solution - Song Lyric App</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Favicon -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- Custom css -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-dark my-3">
<a class="navbar-brand" href="#">
<img src="images/logo.png" alt="Hard Rock Solution">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">
<img src="images/toggler-icon.svg" alt="">
</button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="dropdownId" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
<div class="dropdown-menu" aria-labelledby="dropdownId">
<a class="dropdown-item" href="#">Action 1</a>
<a class="dropdown-item" href="#">Action 2</a>
</div>
</li>
</ul>
</div>
</nav>
<main class="content-area">
<div class="search-bar col-md-6 mx-auto">
<h1 class="text-center">Lyrics Search</h1>
<div class="search-box my-5">
<input id="text" type="text" class="form-control" placeholder="Enter your artist song name"> <span id="artist"></span> <span id="title"></span>
<button id="search-btn" class="btn btn-success search-btn">Search</button>
</div>
</div>
<!-- search results -->
<div id="result" class="search-result col-md-8 mx-auto py-4">
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsOne" class="lyrics-name">Purple Noon</h3>
<p id="artistOne" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnOne" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsTwo" class="lyrics-name">Purple Noon</h3>
<p id="artistTwo" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnTwo" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsThree" class="lyrics-name">Purple Noon</h3>
<p id="artistThree" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnThree" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsFour" class="lyrics-name">Purple Noon</h3>
<p id="artistFour" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnFour" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsFive" class="lyrics-name">Purple Noon</h3>
<p id="artistFive" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnFive" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsSix" class="lyrics-name">Purple Noon</h3>
<p id="artistSix" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnSix" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsSeven" class="lyrics-name">Purple Noon</h3>
<p id="artistSeven" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnSeven" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsEight" class="lyrics-name">Purple Noon</h3>
<p id="artistEight" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnEight" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsNine" class="lyrics-name">Purple Noon</h3>
<p id="artistNine" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnNine" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsTen" class="lyrics-name">Purple Noon</h3>
<p id="artistTen" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnTen" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
</div>
<!-- === search results === -->
<!-- Single Lyrics -->
<div id="lyrics" class="single-lyrics text-center">
<button class="btn go-back">‹</button>
<h2 class="text-success mb-4">Pentatonix - Na Na Na</h2>
<pre class="lyric text-white">
Wont go whistling like the wind blows,
Looking out my window,
Just to see the shine
Maybe you might call it crazy,
How Im acting lately,
Skipping through the sky
I see so clearly,
Why Im always feeling free.
So I sleep when my dreams,
Looking like reality
(Gonna feel it! Na na na...) x4
Gonna feel it!
I know where the greener grass grows
Youll just have to follow
To the other side
Lets go tiptoe on a tight rope,
Fallings only natural
Just spread your wings and fly
Youll see so clearly,
Why Im always feeling free.
So I sleep when our dreams
Looking like reality
(Gonna feel it! Na na na...) x4
Bring it down like
Ohh way oh
Yeah yeah yeah yeah yeah yeah
Break it down like
Ohh way oh
Yeah, yeah, yeah...
All around like
Ohh way oh
Yeah, yeah, yeah...
Sing it loud like!
Ohh way oh
Ah oo oo ooo
Gonna feel it! (Na na na...)
Make it sound like! (Na na na...)
All around like! (Na na na...)
Sing it loud like! (Na na na...)
Gonna feel like! (Na na na...)
</pre>
</div>
</main>
<!-- Optional JavaScript -->
<script src="app.js"></script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- Custom Script Here -->
</body>
</html>
I just combined the 3 for loops into one.
const apiUrl = "https://api.lyrics.ovh/suggest";
const search = document.getElementById("search-btn");
const result = document.getElementById("result");
const text = document.getElementById("text");
const getLyrics = document.getElementsByClassName("get-lyrics");
//search by songs or artist...
function searchSongs(term) {
fetch (`${apiUrl}/${term}`)
.then (response => response.json())
.then (data => {
const lyricsName = document.getElementsByClassName("lyrics-name");
const getLyrics = document.getElementsByClassName("get-lyrics ");
const artist = document.getElementsByClassName("artist");
for (let index = 0; index < lyricsName.length; index++) {
lyricsName[index].innerText = data.data[index].album.title;
artist[index].innerText = data.data[index].artist.name;
//event listener to get lyrics
getLyrics[index].addEventListener("click", function(){
console.log("Song:"+data.data[index].album.title +" By:"+data.data[index].artist.name);
//getLyricsAPI(title, artist);
});
}
document.getElementById("result").style.display = "block";
//console.log(data);
});
}
//event listener to search song or artist
search.addEventListener("click", e => {
//e.preventDefault();
const searchTerm = text.value;
if (!searchTerm) {
alert("please type a song a name");
} else {
searchSongs(searchTerm);
}
})
<!doctype html>
<html lang="en">
<head>
<title>Hard Rock Solution - Song Lyric App</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Favicon -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- Custom css -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-dark my-3">
<a class="navbar-brand" href="#">
<img src="images/logo.png" alt="Hard Rock Solution">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">
<img src="images/toggler-icon.svg" alt="">
</button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="dropdownId" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
<div class="dropdown-menu" aria-labelledby="dropdownId">
<a class="dropdown-item" href="#">Action 1</a>
<a class="dropdown-item" href="#">Action 2</a>
</div>
</li>
</ul>
</div>
</nav>
<main class="content-area">
<div class="search-bar col-md-6 mx-auto">
<h1 class="text-center">Lyrics Search</h1>
<div class="search-box my-5">
<input id="text" type="text" class="form-control" placeholder="Enter your artist song name"> <span id="artist"></span> <span id="title"></span>
<button id="search-btn" class="btn btn-success search-btn">Search</button>
</div>
</div>
<!-- search results -->
<div id="result" class="search-result col-md-8 mx-auto py-4">
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsOne" class="lyrics-name">Purple Noon</h3>
<p id="artistOne" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnOne" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsTwo" class="lyrics-name">Purple Noon</h3>
<p id="artistTwo" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnTwo" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsThree" class="lyrics-name">Purple Noon</h3>
<p id="artistThree" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnThree" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsFour" class="lyrics-name">Purple Noon</h3>
<p id="artistFour" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnFour" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsFive" class="lyrics-name">Purple Noon</h3>
<p id="artistFive" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnFive" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsSix" class="lyrics-name">Purple Noon</h3>
<p id="artistSix" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnSix" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsSeven" class="lyrics-name">Purple Noon</h3>
<p id="artistSeven" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnSeven" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsEight" class="lyrics-name">Purple Noon</h3>
<p id="artistEight" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnEight" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsNine" class="lyrics-name">Purple Noon</h3>
<p id="artistNine" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnNine" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
<div class="single-result row align-items-center my-3 p-3">
<div class="col-md-9">
<h3 id="lyricsTen" class="lyrics-name">Purple Noon</h3>
<p id="artistTen" class="author lead">Album by <span class="artist">Washed Out</span></p>
</div>
<div class="col-md-3 text-md-right text-center">
<button id="btnTen" class="get-lyrics btn btn-success">Get Lyrics</button>
</div>
</div>
</div>
<!-- === search results === -->
<!-- Single Lyrics -->
<div id="lyrics" class="single-lyrics text-center">
<button class="btn go-back">‹</button>
<h2 class="text-success mb-4">Pentatonix - Na Na Na</h2>
<pre class="lyric text-white">
Wont go whistling like the wind blows,
Looking out my window,
Just to see the shine
Maybe you might call it crazy,
How Im acting lately,
Skipping through the sky
I see so clearly,
Why Im always feeling free.
So I sleep when my dreams,
Looking like reality
(Gonna feel it! Na na na...) x4
Gonna feel it!
I know where the greener grass grows
Youll just have to follow
To the other side
Lets go tiptoe on a tight rope,
Fallings only natural
Just spread your wings and fly
Youll see so clearly,
Why Im always feeling free.
So I sleep when our dreams
Looking like reality
(Gonna feel it! Na na na...) x4
Bring it down like
Ohh way oh
Yeah yeah yeah yeah yeah yeah
Break it down like
Ohh way oh
Yeah, yeah, yeah...
All around like
Ohh way oh
Yeah, yeah, yeah...
Sing it loud like!
Ohh way oh
Ah oo oo ooo
Gonna feel it! (Na na na...)
Make it sound like! (Na na na...)
All around like! (Na na na...)
Sing it loud like! (Na na na...)
Gonna feel like! (Na na na...)
</pre>
</div>
</main>
<!-- Optional JavaScript -->
<script src="app.js"></script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- Custom Script Here -->
</body>
</html>
You can pass the event object into your event listener so you will get the which element is clicked. In event listener you can check element's id or what attribute you want to look. If you change the ids of buttons you will get the song information from the buttons.
for (let index = 0; index < getLyrics.length; index++) {
const element = getLyrics[index];
element.addEventListener("click", function(event){
console.log(event.target.getAttribute('id'))
const title = `${index + 1}`;
})
}

Navigating to different pages on single page template

I have a one page template that i am trying to modify so that on clicking particular links the user goes to a new page rather than scroll to a different section. I still want to keep the scroll to a section navigation but I have call to action buttons in those sections that need to go to different pages. The website is a wordpress site
Here is my js code:
$(document).ready(function() {
if ($("a" != ".external")){
$("a").on('click', function(event) {
if ((this.hash !== "/membership-form/") && (this.hash !== "#wood-grain") && (this.hash !== "#gifting") && (this.hash !== "#non-slip") && (this.hash !== "#wpcf7-f4-o1") && (this.hash !== "#carousel-control-next") && (this.hash !== "#carousel-control-prev") && (this.hash !== "#carouselExampleControls")) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top - 100
}, 800, function() {});
}
});
}
});
So on this line if ($("a" != ".external")) I added a class called external to the <a> tags that need to leave the page. I also tried this.hash !== "/membership-form/" to try and target particular <a> tags but it only seems to work with my forms and image gallery that have # references.
How can I get the site to navigate away from the home page to my other pages?
Thanks
UPDATED JS CODE
AOS.init();
var $ = jQuery;
$(document).ready(function() {
$("a").on('click', function(event) {
if (!($(location).attr('href', '/BDWest/membership-form/'))){
if ((this.hash !== "/membership-form/") && (this.hash !== "#wood-grain") && (this.hash !== "#gifting") && (this.hash !== "#non-slip") && (this.hash !== "#wpcf7-f4-o1") && (this.hash !== "#carousel-control-next") && (this.hash !== "#carousel-control-prev") && (this.hash !== "#carouselExampleControls")) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top - 100
}, 800, function() {});
}
}
});
});
UPDATED WITH THE PHP CODE
HEADER.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title><?php bloginfo('name');?> | <?php wp_title(); ?></title>
<link rel="pingback" href="<?php bloginfo('pingback_url');?>" />
<!-- Bootstrap core CSS -->
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div class="loader">
<img alt="first image" src="<?php print IMAGES;?>/3.gif">
</div>
<div class ="parallax-full" id="soon">
<div class="banner-center">
<div class="sticky-top">
<img src="https://via.placeholder.com/468x60?text=Advert" class="img-fluid"/>
</div>
</div>
<div class="hero-textBG">
<div class="logo">
<h1>CLUB BD WEST</h1>
<h2>Logo can be here</h2>
<a class="external" href="/membership-form/"><button type="button" class="btn btn-default">Register Today</button></a>
</div>
<div data-aos="fade-up" data-aos-offset="0">
<div class="scroll-button">
<a href="#home">
<img class="img-fluid" alt="scroll-button" src="<?php print IMAGES;?>/button-down.png">
</a>
<h6>Scroll down</h6>
</div>
</div>
</div>
</div>
navigation.php
<!-- Navigation -->
<nav class="navbar sticky-top navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#home"> <img src="https://via.placeholder.com/70x40?text=Very+Small+Logo" class="img-fluid"/> </a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="#home">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section2">Our Story</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section3">Events</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section4">Gallery</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#section5">Contact Us</a>
</li>
</ul>
</div>
</div>
</nav>
index.php
<!-- Header --><?php get_header(); ?><!--Menu -->
<?php get_template_part('navigation');?><!--Home Section -->
<div class ="parallax" id="BG-2">
<div class="container-fluid">
<div id="home">
<div class="row">
<div class="col-sm-12 text-center">
<div class="content">
<div class="mt-2 col-md-12">
<div data-aos="fade-up">
<h1 class="mt-1">CLUB BD WEST</h1>
<p class="lead">There are no winners or losers, ours is a philosophy of enjoyment through participation and we have organized a range of activities to suit all ages, fitness levels and activity choices.</p>
</div>
</div>
</div>
</div>
</div>
<div class="w-100"> </div>
<section class="top-section">
<div data-aos="fade-up">
<div class="container">
<div class="row">
<div class="col text-center">
<img class="icon" src="<?php PRINT IMAGES;?>/weights-icon.png"></img>
<h3>Badminton</h3>
</div>
<div class="col text-center">
<img class="icon" src="<?php PRINT IMAGES;?>/staff-icon.png"></img>
<h3>Football</h3>
</div>
<div class="col text-center">
<img class="icon" src="<?php PRINT IMAGES;?>/aerobics-icon.png"></img>
<h3>Cricket</h3>
</div>
<div class="col text-center">
<img class="icon" src="<?php PRINT IMAGES;?>/spinning-icon.png"></img>
<h3>Recreational Cycling</h3>
</div>
<div class="col text-center">
<img class="icon" src="<?php PRINT IMAGES;?>/aerobics-icon.png"></img>
<h3>Kayaking</h3>
</div>
<div class="col text-center">
<img class="icon" src="<?php PRINT IMAGES;?>/spinning-icon.png"></img>
<h3>Nature rambling</h3>
</div>
</div>
<div class="row">
<div class="col text-center">
<img src="https://via.placeholder.com/500x60?text=Call+to+action+Club+Sports" class="img-fluid"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center">
<div class="content">
<div class="mt-2 col-md-12">
<div data-aos="fade-up">
<p class="lead">The list of activities is growing, fueled by suggestions from our members.  It’s your club and responds to your needs..</p>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col text-center">
<h3>Our Goals</h3>
<p>To build an online social platform bringing together a diversity of people sharing a common purpose of interaction through sport and recreation.</p>
</div>
<div class="col text-center">
<h3>Our Mission</h3>
<p>To continue growth of both membership and activities developing a multicultural community with a social conscience. </p>
</div>
<div class="col text-center">
<h3>Our Vision</h3>
<p>To add to the quality of life, build cohesion in communities and enrich society.</p>
</div>
</div>
</div>
</section>
</div>
</div><!-- Container End -->
<hr class="content-seperator"></hr>
<div id="section2">
<div data-aos="fade-up">
<div class="container">
<div class="row">
<div class="col-sm-12 text-center">
<h1>Our Story</h1>
<p>It all started when a group of friends got together for an impromptu game of badminton. The shared love of the game and the company of friends was a compelling mix and very quickly these random get togethers developed into a regular event.</p> <p>The group began to grow rapidly, first from within the circle of friends and later extending to others that were exposed to the group and drawn to it.  At this point it was evident that a structure was required to communicate with group members and so BD West was formed.</p> <p>BD West is now a not for profit social club with over 200 members and plans to grow into a multicultural community of like-minded people brought together by the love of sport, recreation and the harmony of social connection. </p>
</div>
</div>
<br>
<div class="row">
<div class="col-sm-12 text-center">
<h2>Our Management Team</h2>
</div>
<div class="col-sm-12 text-center">
<img src="https://via.placeholder.com/500x60?text=Call+to+action+Management+Team" class="img-fluid"/>
</div>
</div>
</div>
</div>
</div>
<hr class="content-seperator"></hr>
</div><!-- BG End -->
<div class ="parallax" id="BG-3"> <div class="col-sm text-center"> <img src="https://via.placeholder.com/468x60?text=Advert" class="img-fluid"/> </div>
<div id="section3">
<div class="container">
<div class="row">
<div class="col-lg-12 mb-sm-0 text-center">
<div class="content">
<div data-aos="fade-up">
<h3 class="mt-2">Events</h3>
<p class="lead">Here are some of our latest events</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center">
</div>
</div>
</div><!--./container -->
</div> <!-- ./section3 -->
<hr class="content-seperator"></hr>
</div><!--./ BG3 --> <!-- Pricing Table -->
<div class ="parallax" id="BG-1">
<div class="container">
<div class="row">
<div class="col-lg-12 mb-3 mb-sm-0 text-center">
<div id="section4">
<div class="content">
<div data-aos="fade-up">
<h3 class="mt-2">Gallery</h3>
</div>
</div>
</div>
</div>
</div>
</div>
<hr class="content-seperator-yellow"></hr>
</div> <!-- Contact Form and Location -->
<div class ="parallax" id="BG-2">
<div id="section5">
<div class="container">
<div class="row">
<div class="col-12 text-center">
<div data-aos="fade-up">
<div class="content">
<h3 class="mt-2">Contact Us</h3>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<div data-aos="fade-up">
<?php echo do_shortcode('[contact-form-7 id="16" title="Contact Us"]');?>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<div data-aos="fade-up">
<p class="lead">BD West Incorporated</p>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<div data-aos="fade-up">
<div class="content">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Footer Section -->
<?php get_footer();?>
if you want to link through jQuery it would be like this:
$(location).attr('href', 'http://stackoverflow.com')
But it is highly recommended to do this with pure Javascript it best simulates an HTTP redirect, and it would go like this:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
It's better to use window.location.replace(...), because the replace() doesn't keep the page they'd come from in the session history, which avoids having the users stuck in a never-ending back-button loop.

How to show data when using API?

Im trying to get data from an API using ajax request. I did it but im not sure how to show the information to the client. I want to search by artist and show their songs. Here is my code and link to the api. Please help me!
https://rapidapi.com/brianiswu/api/genius?endpoint=apiendpoint_d2f41ea4-7d5c-4b2d-826a-807bffa7e78f
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MusicApp</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<header>
<div class="container">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">MusicApp</a>
</div>
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Lyrics</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</nav>
</div>
</header>
<div class="container">
<div class="row" style="margin-top:30px;">
<div class="col-sm-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Search</h3>
</div>
<div class="panel-body">
<div class="form-group">
<div class="row">
<div class="col-sm-4">
<img class="thumbnail img-responsive" src="images/notes.jpg">
</div>
<div class="col-sm-8">
<input type="checkbox" class="form-check-input" id="sort">
<label class="form-check-label" for="sort">Sort</label>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label for="artist">Artist:</label>
<textarea class="form-control" rows="1" id="artist"></textarea>
</div>
</div>
</div>
</div>
<div class="panel-footer" style="height:55px;">
<button type="button" id="postComment" class="btn btn-primary pull-right publish"><span
class="glyphicon glyphicon-globe"></span> Search
</button>
</div>
</div>
</div>
<div class="col-sm-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Results</h3>
</div>
<ul class="list-group" style="min-height:241px;" id="contentList">
<li class="list-group-item" style="display:none" id="cloneMe">
<div class="row">
<div class="col-sm-2 col-xs-3">
<img src="images/notes.jpg" class="thumbnail img-responsive">
</div>
<div class="col-sm-7 col-xs-6">
<h4>Shakira</h4>
<p id="songName">some result </p>
<p id="lyricsLink">some result</p>
</div>
<div class="col-sm-3 col-xs-3">
<button type="button" class="btn btn-danger pull-right remove-post"><span
class="glyphicon glyphicon-remove"></span><span class="hidden-xs"> Delete</span>
</button>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
$(document).ready(function(){
var api="1f57380a81msh394cf453f4d1e73p1a0276jsnab0cd43f0df7";
$('#postComment').click(function(){
artistName=$('#artist').val();
console.log(artistName);
var settings = {
"async": true,
"crossDomain": true,
"url": "https://genius.p.rapidapi.com/search?q=" + artistName,
"method": "GET",
"headers": {
"x-rapidapi-host": "genius.p.rapidapi.com",
"x-rapidapi-key": "1f57380a81msh394cf453f4d1e73p1a0276jsnab0cd43f0df7"
}
}
$.ajax(settings)
.done(function (response) {
console.log(response.response.hits);
response.response.hits.forEach(r => {
var miniMe = $('#cloneMe').clone();
miniMe.attr('id', r.result.id);
console.log(r.result.header_image_url);
miniMe.find('img').attr('src', r.result.header_image_url);
miniMe.find('h4').text(artistName);
miniMe.find('#songName').html(r.result.full_title);
miniMe.find('#lyricsLink').html(r.result.url);
miniMe.find('button').click(function () {
miniMe.remove();
});
miniMe.find('checkbox').click(function(){
})
miniMe.show();
$('#contentList').append(miniMe);
});
});
return false;
});
});
</script>
</html>
You can iterate through the response with using this as your ajax block;
$.ajax(settings)
.done(function (response) {
// sort the response alphabetically
response.response.hits.sort((a,b) => (a.result.full_title > b.result.full_title) ? 1 : (b.result.full_title > a.result.full_title) ? -1 : 0);
response.response.hits.forEach(r => {
var miniMe = $('#cloneMe').clone();
miniMe.attr('id', r.result.id);
miniMe.find('img').attr('src', r.result.header_image_url);
miniMe.find('h4').text(artistName);
miniMe.find('p').html(r.result.full_title);
miniMe.find('button').click(function () {
miniMe.remove();
});
miniMe.show();
$('#contentList').append(miniMe);
});
});
You can see the working demo in codepen and you can look into this link if you want to learn about sort() function and how it works in JavaScript.

Categories

Resources