Javascript not firing when page is loaded in a div - javascript

So I have this issue, I want to use vanilla JavaScript because I don't like how bloated JQuery is. Now, the problem I have is when I load my file into the div withe the following code:
async function loadPage (pagename) {
await fetch(pagename, {
headers: {
"Content-Type": "text/html; charset=utf-8"
}
})
.then((response) => response.text())
.then((html) => {
document.getElementById("Loader").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
my JavaScript in the page doesn't fire.
I have tried running JavaScript in the file and also with external files.
When I put the JavaScript file for this HTML in the main page it fires, but it is littered with errors. When I use the JQuery load function it works fine though, is there any way to get this right in vanilla JavaScript or am I gonna have to use JQuery??
HTML for details.html:
<!DOCTYPE html>
<html lang="en">
<head>
<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="stylesheet" href="css/autocomplete.css">
<link rel="stylesheet" href="css/details.css">
<link rel="stylesheet" href="css/tablestyles.css">
<title>Search</title>
</head>
<body>
<!-- Enter search criteria here -->
<div id="top">
<button onclick="search();">Search</button>
<div class="autocomplete" style="width:300px;">
<input type="text" name="searchPhrase" id="searchPhrase" placeholder="Search Phrase" autocomplete="off">
</div>
<!-- Options for autocomplete -->
<div id="displaydiv">
</div>
</div>
<div id="results">
</div>
</body>
<script src="js/autocomplete_input.js"></script>
<script src="js/tablecreator.js"></script>
<script src="js/details.js"></script>
</html>
loadPage is called by main.js
function openSearch(){
loadPage('details.html');
}
I tried replicating it in codesandbox!

Related

implementing search bar in api

So I am struggling with APIs and how to handle them. I am currently stuck on an error and haven't been able to figure out how to fix it. My goal with this project is to be able to use the cocktailapi and have a search bar where a user can search by an ingredient, ie gin. I get the below error when I run the code. I'm just not sure how to fix this.
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
at extrafile.js:25:34
I also get the below error why I type input in the search bar.
Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')extrafile.js:45
at displayIngredientResults (extrafile.js:45:26)
at HTMLInputElement. (extrafile.js:18:5)
Any advice is greatly appreciated.
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
const drinks = document.getElementById('drinks1');
const searchBar = document.getElementById('search-Bar');
let ingredientResults = [];
searchBar.addEventListener('keyup', (e) => {
const searchString = e.target.value.toLowerCase();
const filteredIngredients= ingredientResults.filter((drinks) => {
return (
drinks.strIngredient.toLowerCase().includes(searchString)
);
});
displayIngredientResults(filteredIngredients);
});
const loadIngredientResults = () => {
try {
const res = fetch('https://www.thecocktaildb.com/api/json/v1/1/filter.php?i='+ searchBar.value)
.then(res => {return res.json()});
// ingredientResults = res.JSON().results;
// displayIngredientResults(ingredientResults);
} catch (err) {
console.error(err);
}
};
const displayIngredientResults = (results) => {
const htmlString = results
.map((drinks) => {
return `
<div class="card">
<div class="card-body">
<h2>${drinks.strIngredient}</h2>
</div>
</div>
`;
})
.join('');
drinks.innerHTML = htmlString;
};
loadIngredientResults();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<link rel="stylesheet" href="styles.css" />
<script src="searchbyingredient.js"></script>
</head>
<body>
<div class="container">
<h1>✨Cocktails ✨</h1>
<div id="searchWrapper">
<input
type="text"
name="searchBar"
id="searchBar"
placeholder="Search for a Cocktail"
/>
</div>
<ul id="cocktailsList"></ul>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cocktail App</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>
<br>
<div class="card" style="width: 18rem;">
<div class="card-body" id = " card">
<label for="site-search" ></label>
<body>
<div class="container2">
<div id="searchWrapper">
<input
type="text"
name="search-Bar"
id="search-Bar"
placeholder="Enter Main Ingredient"
/>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script src="extrafile.js"></script>
<!-- <script src="searchbyingredient.js"></script> -->
</body>
</html>
A couple issues here:
The following line sets drinks as null or undefined, since your HTML does not already contain a div with the id of "drinks1".
const drinks = document.getElementById('drinks1');
If you want to create the element in Javascript, you'll need to use a library like jQuery to help you do that like this https://api.jquery.com/add/, or use vanilla javascript like this https://www.javascripttutorial.net/dom/manipulating/create-a-dom-element/
Also, you never set the value of ingredientResults so it is always [], also the function loadIngredientResults returns a promise, and you cannot depend on ingredientResults to not be [] when you execute the following line:
const filteredIngredients= ingredientResults.filter((drinks) => {
return (
drinks.strIngredient.toLowerCase().includes(searchString)
);
});
Consider creating an async/await asynchronous call on keyup and ensuring that the API call has succeeded or that filteredIngredients has a value.

JS script doesn't work in a Thymeleaf template

I'm trying to add a default 404 error page to my Spring app, and I thought it would be nice to add an animate template like that: https://codepen.io/wikyware-net/pen/xywexE
The whole idea is a validation of form and redirection to the error page, if it fails.
Basically, redirection works fine, but the problem I have is I can not make the JS part running (the tost doesn't pop up :-/)...
Here's how my error page looks like:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Ooops... Something went wrong!</title>
<meta name="description" content="Создание адаптивного сайта"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" th:href="#{/css/error.css}"/>
<script type="text/javascript" th:src="#{/static/js/error.js}"></script>
</head>
<body>
<div class="ag-page-404">
<div class="ag-toaster-wrap">
<div class="ag-toaster">
<div class="ag-toaster_back"></div>
<div class="ag-toaster_front">
<div class="js-toaster_lever ag-toaster_lever"></div>
</div>
<div class="ag-toaster_toast-handler">
<div class="ag-toaster_shadow"></div>
<div class="js-toaster_toast ag-toaster_toast js-ag-hide"></div>
</div>
</div>
<canvas id="canvas-404" class="ag-canvas-404"></canvas>
<img class="ag-canvas-404_img"
src="https://raw.githubusercontent.com/SochavaAG/example-mycode/master/pens/404-error-smoke-from-toaster/images/smoke.png">
</div>
<div>
<a th:href="#{/home}" target="_blank" class="btn-primary">Go back</a>
</div>
</div>
</body>
Both CSS and JS code I use, is included in the template I attached at the very beginning.
Here's also the snapshot of the project's resources structure:
What am I doing wrong here?
What are best practices in importing such a HTML template into a Spring Boot/Thymeleaf project?
Thank you in advance for your help.
Kind regards,
Matthew
EDIT:
So I changed my html page to that form:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Ooops... Something went wrong!</title>
<meta name="description" content="Создание адаптивного сайта"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" th:href="#{/css/error.css}"/>
</head>
<body>
<div class="ag-page-404">
<div class="ag-toaster-wrap">
<div class="ag-toaster">
<div class="ag-toaster_back"></div>
<div class="ag-toaster_front">
<div class="js-toaster_lever ag-toaster_lever"></div>
</div>
<div class="ag-toaster_toast-handler">
<div class="ag-toaster_shadow"></div>
<div class="js-toaster_toast ag-toaster_toast js-ag-hide"></div>
</div>
</div>
<canvas id="canvas-404" class="ag-canvas-404"></canvas>
<img class="ag-canvas-404_img" src="https://raw.githubusercontent.com/SochavaAG/example-mycode/master/pens/404-error-smoke-from-toaster/images/smoke.png">
</div>
</div>
<div>
<a th:href="#{/home}" target="_blank" class="btn-primary">Go back</a>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" th:src="#{/js/error.js}"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</div>
</body>
Plus, I also updated my build.gradle file:
buildscript {
ext {
springBootVersion = '2.0.5.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
plugins {
id 'war'
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'pl.mpas'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-web')
compile group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: '2.3.7.RELEASE'
compile group: 'org.webjars', name: 'bootstrap', version: '3.3.6'
compile group: 'org.webjars', name: 'bootstrap-datepicker', version: '1.0.1'
compile group: 'org.webjars.bower', name: 'jquery', version: '3.5.1'
runtime('org.springframework.boot:spring-boot-devtools')
runtime('com.h2database:h2')
runtime('mysql:mysql-connector-java')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile('org.apache.struts:struts2-core:2.3.16.1')
providedCompile('javax.servlet.jsp:jsp-api:2.1')
providedCompile('javax.servlet:javax.servlet-api:3.1.0')
}
Thanks to that, I no longer see any errors in the browser's console.
However... JS still doesn't work as expected. :-/
Your files structure looks good. you have added your js file in error page by
<script type="text/javascript" th:src="#{/static/js/error.js}"></script>
but I don't thing you need to mention static in your source URL for JS, Change it to
<script type="text/javascript" th:src="#{/js/error.js}"></script>
also please add the below dependencies in your pom.xml for jQuery and Bootstrap
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.6</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap-datepicker</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>1.9.1</version>
</dependency>
change your error.html file as shown below
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Ooops... Something went wrong!</title>
<meta name="description" content="Создание адаптивного сайта"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" th:href="#{/css/error.css}"/>
</head>
<body>
<div class="ag-page-404">
<div class="ag-toaster-wrap">
<div class="ag-toaster">
<div class="ag-toaster_back"></div>
<div class="ag-toaster_front">
<div class="js-toaster_lever ag-toaster_lever"></div>
</div>
<div class="ag-toaster_toast-handler">
<div class="ag-toaster_shadow"></div>
<div class="js-toaster_toast ag-toaster_toast js-ag-hide"></div>
</div>
</div>
<canvas id="canvas-404" class="ag-canvas-404"></canvas>
<img class="ag-canvas-404_img" src="https://raw.githubusercontent.com/SochavaAG/example-mycode/master/pens/404-error-smoke-from-toaster/images/smoke.png">
</div>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" th:src="#{/js/error.js}"></script>
</body>
</html>
now it will work fine. Let me know if any doubt.
Refer:https://www.springboottutorial.com/spring-boot-with-jquery-and-bootstrap-web-jars
A couple of notes:
Change your JavaScript reference for your error.js script to this:
<script type="text/javascript" th:src="#{/js/error.js}"></script>
There is no need to include the /static portion of the URL.
Also, have you included jQuery in the page? For example:
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
You will see an error in the browser's console if jQuery is not available.
Try to change your JavaScript reference in your HTML page:
<link rel="stylesheet" href="../static/css/error.js" type="text/javascript" th:href="#{/error.js}">
All right guys, I finally made it running. In my case the problem was a lack of jQuery's script tag in html's head section. I used Google's CDN hosting:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
So the final, working version of my page looks as follows:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Ooops... Something went wrong!</title>
<meta name="description" content="Создание адаптивного сайта"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" th:href="#{/css/error.css}"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="ag-page-404">
<div class="ag-toaster-wrap">
<div class="ag-toaster">
<div class="ag-toaster_back"></div>
<div class="ag-toaster_front">
<div class="js-toaster_lever ag-toaster_lever"></div>
</div>
<div class="ag-toaster_toast-handler">
<div class="ag-toaster_shadow"></div>
<div class="js-toaster_toast ag-toaster_toast js-ag-hide"></div>
</div>
</div>
<canvas id="canvas-404" class="ag-canvas-404"></canvas>
<img class="ag-canvas-404_img"
src="https://raw.githubusercontent.com/SochavaAG/example-mycode/master/pens/404-error-smoke-from-toaster/images/smoke.png">
</div>
</div>
<div>
<a th:href="#{/home}" target="_blank" class="btn-primary">Go back</a>
</div>
<script src="webjars/jquery/3.5.1/jquery.min.js"></script>
<script src="webjars/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script type="text/javascript" th:src="#{/js/error.js}"></script>
</div>
</body>
Thanks again for your help! Cheers!

Fetching HTML and changing document body

Please, do not mark this as a duplicate. I tried everything I could, and this isn't working. I have experience in Javascript. It isn't my first time using it
Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JUST_LOAD_ALREADY</title>
<!-- <script defer src="/index.js"></script> -->
</head>
<body>
PLEASSDETY FGUIRWFVUI
<script>
function loadContent() {
fetch("/content.html")
.then((res) => res.text())
.then((text) => (document.body.innerHTML = text));
}
loadContent()
</script>
</body>
</html>
content.html:
<h1>Content page</h1>
Expected page content inside body after everything loads:
<h1>Content</h1>
Actual page content inside body:
PLEAS
Its neither my frustration text nor content.html's content. This is killing me please help tell me why this is happening. These are the only two files I have + a package.json for running sirv
Adding a div with an id and changing its innerHTML seems to work, could be "killing yourself" due to having the script inside the body like #MarkusZeller said. The code below worked:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JUST_LOAD</title>
<!-- <script defer src="/index.js"></script> -->
</head>
<body>
PLEASSDETY FGUIRWFVUI
<main id="content"></main>
<script>
function loadContent() {
fetch("/content.html")
.then((res) => res.text())
.then((text) => (document.getElementById("content").innerHTML = text));
}
loadContent();
</script>
</body>
</html>
Alternatively put this in the head
window.addEventListener("load",() => {
fetch("/content.html")
.then(res => res.text())
.then(text => document.body.innerHTML = text);
})

How to use jQuery UI from Blazor component

I am working through some Blazor examples, and while trying to work with some JSInterop solutions, I ran into an issue with jQuery UI elements. I am not a proficient Javascript programmer, but I am proficient enough with .NET so I may be missing something simple. The first jQuery UI component I have tried to work with is the "resizable" component, found here: https://jqueryui.com/resizable/
Here is what my current code looks like:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width">
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/site.css" rel="stylesheet" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<app>Loading...</app>
<script src="_framework/blazor.server.js"></script>
<script>
$( function() {
$( "#resizable" ).resizable();
});
</script>
</body>
</html>
I am certain that the issue isn't with loading the libraries, and I have placed the script after loading blazor.server.js.
Now, my Index.cshtml has the following in the html portion:
<body>
<div class="container-fluid">
<div id="resizable" class="ui-widget-content">
<div class="row row-no-gutters" style="width: 100%; height: 50%">
<h3 class="ui-widget-header">Resizable</h3>
</div>
</div>
</div>
</body>
Ideally, this would yield a resizable div, but the resulting html element is not resizable. From my understanding, Blazor JSInterop no longer requires JS functions to be registered. What am I doing wrong?
The problem is that of timing: your jQuery function executes before your Blazor app has rendered.
The way I solved this is by replacing the "onready" ($(...)) function with a named function (e.g. onBlazorReady) that I then invoke from my Blazor's MainLayout component at the right time.
The right time being OnAfterRender.
For example:
MainLayout.razor:
#code {
[Inject]
protected IJSRuntime JsRuntime { get; set; }
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
JsRuntime.InvokeVoidAsync("onBlazorReady");
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width">
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/site.css" rel="stylesheet" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<app>Loading...</app>
<script src="_framework/blazor.server.js"></script>
<script>
onBlazorReady() {
$("#resizable").resizable();
});
</script>
</body>
</html>
As you can see, I'm injecting IJSInterop so that I can call my onBlazorReady JS function after the LayoutComponent has rendered.
Works fine for me like this, to add datepicker from jquery ui:
Razor component file.
#code {
protected override async void OnAfterRender(bool firstRender)
{
await jsRuntime.InvokeVoidAsync("addDatePicker");
base.OnAfterRender(firstRender);
}
}
Global razor file:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Magiro.Blazor</title>
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<app>
#(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))
</app>
<script src="_framework/blazor.server.js"></script>
<script>
window.addDatePicker = () => {
$(".datepicker").datepicker();
}
</script>
</body>
</html>
There is no need any more to add a method in the global index page (_Hosts.cshtml in ASP.NET Core 5.0), which would fill those file with view-specific logic and dependencies. At least with v5 we have IJSObjectReference allowing us to call $('table').DataTable() directly from our .razor file like this:
<table>
<thead>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<!-- your data -->
</tbody>
</table>
#code {
[Inject]
protected IJSRuntime JSRuntime { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender) {
if (firstRender) {
var jQuery = await JSRuntime.InvokeAsync<IJSObjectReference>("$", "table");
await jQuery.InvokeVoidAsync("DataTable");
}
}
}
It's also possible to pass options to the plugin with an anonymous type. For example, to disable the search, we'd call in JS
$('#example').dataTable({
"searching": false
});
In Blazor we create an anonymous type with the same structure and pass it as parameter to the DataTable call:
var options = new {
searching = false
};
await jQuery.InvokeVoidAsync("DataTable", options);
The most probable cause is timing. The jQuery function gets executed before the DOM elements exists.
You should register the JS code as an interop function and call that after in OnAfterRender event.
Normally you don't need any JQuery function like ready, you can simply put those all required code into your custom js function which should run on ON_LOAD of your component as said by #Sipke Schoorstra in above answer

jquery mobile listview not formatting the list

guys im trying to implement jquery mobile listview just as this example with thumbnails
http://demos.jquerymobile.com/1.4.3/listview/
however, if i copy past the source code into my html it works fine, however if im trying to add it to the list using javascript it doesnt work.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>App Title</title>
<!-- Framework's CSS Files -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<!-- Our CSS Files -->
<link rel="stylesheet" href="css/custom.css">
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
<h2>PolyMovie</h2>
</div>
<div data-role="main" class="ui-content">
<form onsubmit="getMovies(event)">
<input type="search"id="searchText"/>
</form>
</div>
<ul data-role="listview" id="movies">
<!-- if i add it here it works fine, but using the javascript the image is not formatted -->
</ul>
<div data-role="footer">
<h2>Copyright 2018</h2>
</div>
</div>
<!-- APIs js scripts -->
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- Our js Scripts -->
<script type="text/javascript" src="js/main.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</body>
</html>
and this is my javascript function
function getMovies(event) {
var searchText = document.getElementById("searchText").value;
event.preventDefault();
axios.get("https://api.themoviedb.org/3/search/movie?query=" + searchText + "&api_key=" + api_key + "&language=en-US&page=1&include_adult=false")
.then((response) => {
console.log(response);
let movies = response.data.results;
let output = '';
$.each(movies, (index, movie) => {
output += `
<li><a href="#">
<img src="http://image.tmdb.org/t/p/w185/${movie.poster_path}">
<h2>${movie.title}</h2>
<p>${movie.release_date}</p></a>
</li>
`
});
document.getElementById("pageone").innerHTML = "<ul data-role='listview' id='movies'>"+output+"</ul>";
})
.catch((err) => {
console.log(err);
});
}
I really dont understand why this is happening, but i think it's because of the innerhtml
any help would be appreciated
Whenever a jquery element is added dynamically, the element needs to be refreshed for the styling to take effect. The format is:
$(selector).elementName("refresh");
so in your case it would be
$("#movies").listview("refresh");

Categories

Resources