How to call a function on video end ? (HTML5 and mediaelementjs) - javascript

i am using mediaelementjs for playing video on my website but i need to call some
function at the END/pause of video.So please tell me how an i do this?
Thanks in advance

You need to create a new EventListener for the ended and pause events.
Example:
YourMediaElement.addEventListener('ended', function(){
//Your Code goes here
});
Update: This method should be applied on the success handler of creating the element, as is shown in the example on the bottom of the page at MediaElementJS.com
success: function (YourMediaElement, domObject) {
// add event listener
YourMediaElement.addEventListener('ended', function(e) {
//Do Stuff here
}, false);

May be it will be useful for someone...
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=9">
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
<title>Media Website</title>
<script type="text/javascript" src="build/jquery.js"></script>
<script type="text/javascript" src="build/mediaelement-and-player.min.js"></script>
<link href="build/mediaelementplayer.min.css" rel="Stylesheet" />
<link href="build/mejs-skins.css" rel="Stylesheet" />
<style type="text/css">
html, body
{
overflow: hidden;
}
*
{
margin: 0px;
padding: 0px;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
var height = getURLParameters('height');
$("#player1").css("height", height + "px");
var width = getURLParameters('width');
$("#player1").css("width", width + "px");
});
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
function ChangeSize(h, w) {
$("#player1").css("height", h + "px");
$("#player1").css("width", w + "px");
}
var videoLink;
var videoLinkType;
var posterLink;
function SetPosterLink(p) {
posterLink = p;
$("#player1").attr("poster", posterLink);
}
function SetVideoLink(l, t) {
videoLink = l;
videoLinkType = t;
$("#player1").attr("src", videoLink);
$("#player1").attr("type", videoLinkType);
}
var player;
function CreatePlayer() {
player = MediaElement('player1',
{
success: function (me) {
// me.play();
me.addEventListener('ended', function (e) {
//Do Stuff here
alert('ended');
}, false);
}
});
}
function Play() {
player.play();
}
function Pause() {
player.pause();
}
function Stop() {
player.pause();
}
</script>
</head>
<body style="overflow: hidden; margin: 0 !important; padding: 0 !important;">
<video controls="none" preload="none" width="0" height="0" style="margin: 0 !important;
padding: 0 !important; overflow: hidden;" id="player1" name="mplayer1" src=""
type="" poster="">
</video>
</body>
</html>

Related

How to make a tooltip with the same look and feel as when we add "title" attribute to an element?

I am trying to replicate the look and feel of the tooltip when we add the "title" attribute to an element.
Tooltip should be hovarable
Tooltip should be dismissable by pressing the Esc key
Currently, my custom tooltip is not hoverable. Also the look and feel is not matched with - https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_global_title
Any help is really appreciated and thanks in advance
const tooltipTrigger = document.querySelector(".tooltip-trigger");
const tooltipText = document.querySelector(".tooltip-text");
tooltipTrigger.addEventListener("mouseenter", showTooltip);
tooltipTrigger.addEventListener("mouseleave", hideTooltip);
tooltipText.addEventListener("keydown", dismissTooltip);
function showTooltip() {
tooltipText.style.visibility = "visible";
}
function hideTooltip() {
tooltipText.style.visibility = "hidden";
}
function dismissTooltip(event) {
if (event.keyCode === 27) {
tooltipText.style.visibility = "hidden";
}
}
.tooltip-text {
visibility: hidden;
position: absolute;
background-color: #000;
color: #fff;
padding: 4px;
z-index: 1;
}
.tooltip-trigger{
cursor: pointer;
}
.tooltip-trigger:hover .tooltip-text {
visibility: visible;
}
<!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="styles.css" />
<title>Tooltip</title>
</head>
<body>
<span class="tooltip-trigger" aria-describedby="tooltip-text"
>Hover over me</span
>
<div id="tooltip-text" class="tooltip-text" role="tooltip">
This is the tooltip text
</div>
<script src="script.js"></script>
</body>
</html>
const tooltipTrigger = document.querySelector(".tooltip-trigger");
const tooltipText = document.querySelector(".tooltip-text");
let timeout = null;
tooltipTrigger.addEventListener("mouseenter", showTooltip);
tooltipTrigger.addEventListener("mouseleave", hideTooltip);
window.addEventListener("keydown", dismissTooltip);
function showTooltip(event) {
timeout = setTimeout(() => {
tooltipText.style.visibility = "visible";
tooltipText.style.left = `${event.clientX}px`
tooltipText.style.top = `${event.clientY}px`
}, 1000)
}
function hideTooltip() {
clearTimeout(timeout);
timeout = null;
tooltipText.style.visibility = "hidden";
}
function dismissTooltip(event) {
if (event.key === 'Escape') {
tooltipText.style.visibility = "hidden";
}
}
.tooltip-text {
visibility: hidden;
position: absolute;
background-color: #000;
color: #fff;
padding: 4px;
z-index: 1;
}
.tooltip-trigger {
cursor: pointer;
}
<!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="styles.css" />
<title>Tooltip</title>
</head>
<body>
<span class="tooltip-trigger" aria-describedby="tooltip-text">Hover over me</span
>
<div id="tooltip-text" class="tooltip-text" role="tooltip">
This is the tooltip text
</div>
<script src="script.js"></script>
</body>
</html>
The ultimate answer is in fact, you can't.
You can't replicate the exact behavior of a tooltip generated by a title attribute, simply because their appearance and behavior can be dramatically different across browsers, devices and OS.
You can certainly try to approach very close what it looks like on a particular browser/device/OS, but won't probably be able to replicate exactly everything everywhere. Note that doing user agent detection to finetune is most often a bad idea.

How do I pass on an image which will be selected from a group (on click) to anther html where it will be displayed using javascript?

The first html will contain a slideshow of images from where the user will get to choose one on click. Then the user will be redirected to the next html in which the selected image will be displayed.
This is my javascript code for the html where the image will be selected
var whichImages;
function displayImage(){
document.getElementsByClassName("image").onclick = whichImages;
return whichImages.join('');
}
sessionStorage.setItem(whichImages);
This is my javascript code for the html where the selected image will be displayed
var mainChar = sessionStorage.getItem(whichImages);
function showImage2(){
document.getElementById("img") = mainChar;
}
showImage2();
I think this is the behaviour you want. I changed to localStorage, so that is available if you open a new tab.
select_images.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" />
<title>Document</title>
</head>
<body>
<div>
See selected images
</div>
<img
src="https://images.pexels.com/photos/56866/garden-rose-red-pink-56866.jpeg?auto=compress&cs=tinysrgb&w=400"
alt=""
/>
<img
src="https://images.pexels.com/photos/4043324/pexels-photo-4043324.jpeg?auto=compress&cs=tinysrgb&w=400"
alt=""
/>
<img
src="https://images.pexels.com/photos/7003188/pexels-photo-7003188.jpeg?auto=compress&cs=tinysrgb&w=400"
alt=""
/>
<img
src="https://images.pexels.com/photos/6765585/pexels-photo-6765585.jpeg?auto=compress&cs=tinysrgb&w=400"
alt=""
/>
<script>
//initializing with an empty array
if (!localStorage.getItem("images")) {
localStorage.setItem("images", JSON.stringify([]));
}
//changed to local storage for it to work when opening a new tab
//look in the local storage to see which images are saved, to apply the border to them (if page is refreshed)
JSON.parse(localStorage.getItem("images"))?.forEach((url) => {
document.querySelectorAll("img").forEach((img) => {
if (img.src == url) {
img.style.border = "10px solid green";
}
});
});
//bind the click event on each img, if the img exists it will remove, if it doesn't exists, add it
document.querySelectorAll("img").forEach((img) => {
img.addEventListener("click", (e) => {
let imgSrcs = JSON.parse(localStorage.getItem("images"));
const currentImgSrc = e.currentTarget.src;
if (imgSrcs.includes(currentImgSrc)) {
const filtered = imgSrcs.filter((img) => img !== currentImgSrc);
localStorage.setItem("images", JSON.stringify(filtered));
e.currentTarget.style.border = "none";
return;
}
imgSrcs.push(currentImgSrc);
localStorage.setItem("images", JSON.stringify(imgSrcs));
e.currentTarget.style.border = "10px solid green";
});
});
</script>
</body>
</html>
see_images.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" />
<title>Document</title>
</head>
<body>
<div>
Select Images
</div>
<script>
if (localStorage.getItem("images")) {
const imgSrcs = JSON.parse(localStorage.getItem("images"));
if (imgSrcs.length === 0) {
document.body.append("No images selected");
}
imgSrcs.forEach((url) => {
if (url) {
const img = document.createElement("img");
img.src = url;
document.body.append(img);
}
});
} else {
document.body.append("No images selected");
}
</script>
</body>
</html>

Cannot load html2 canvas

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<script src="https://unpkg.com/jspdf#latest/dist/jspdf.umd.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
type="text/javascript"
src="/js/lib/dummy.js"
></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style id="compiled-css" type="text/css">
img {
width: 100px;
height: 50px;
}
/* EOS */
</style>
<script id="insert"></script>
</head>
<body>
<head>
<style>
#CHARSET "UTF-8";
.page-break {
page-break-after: always;
page-break-inside: avoid;
clear:both;
}
.page-break-before {
page-break-before: always;
page-break-inside: avoid;
clear:both;
}
#html-2-pdfwrapper{
position: absolute;
left: 20px;
top: 50px;
bottom: 0;
overflow: auto;
width: 600px;
}
</style>
</head>
<body>
<button onclick="generate()">Generate PDF</button>
<div id="html-2-pdfwrapper">
<h3 class= "first_header-txt">
Net Weight (KG/LB)
</h3>
<h3 class="first-txt">
Temp1
</h3>
<h3 class= "second_header-txt">
Gross Weight (KG/LB)
</h3>
<h3 class="second-txt">
Temp2
</h3>
<h3 class="details">
Temp3
</h3>
<div>
</body>
<script>
window.jsPDF = window.jspdf.jsPDF
var base64Img = null;
margins = {
top: 70,
bottom: 40,
left: 30,
width: 550
};
generate = function()
{
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.setFontSize(18);
pdf.html(document.getElementById('html-2-pdfwrapper'),
{
'x' : margins.left, // x coord
'y' : margins.top,
'width' : margins.width,// max width of content on PDF
'callback' : function(pdf) {
pdf.save('NetWeight.pdf');
}
});
var iframe = document.createElement('iframe');
iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:650px; padding:20px;');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
};
</script>
<script>
var ExcelToJSON = function() {
this.parseExcel = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function(sheetName) {
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
var obj = JSON.parse(json_object);
var length = obj.length;
for (var i = 0; i < length; i++) {
var netWeight = obj[i]["netWeight"];
var grossWeight = obj[i]["grossWeight"];
var details = obj[i]["details"];
chumpage(netWeight, grossWeight, details);
}
})
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
function chumpage(netWeight, grossWeight, details) {
var netWeight = netWeight;
var grossWeight = grossWeight;
var details = details;
var netWeightKG = Math.trunc(grossWeight * 2.2);
var grossWeightKG = Math.trunc(grossWeight * 2.2);
chump = document.getElementsByClassName("first-txt");
chump2 = document.getElementsByClassName("second-txt");
chump3 = document.getElementsByClassName("details");
chump[0].style.fontSize = "100px";
chump2[0].style.fontSize = "100px";
chump3[0].style.fontSize = "50px";
for (var i = 0; i < chump.length; i++) {
chump[i].innerText = netWeight + '/' + netWeightKG;
chump2[i].innerText = grossWeight + '/' + grossWeightKG;
chump3[i].innerText = details;
}
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
}
</script>
<form enctype="multipart/form-data">
<input id="upload" type=file name="files[]">
</form>
<script>
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>
Whenever I try to generate pdf on the website I get the error cannot load html2 canvas and the pdf is blank. The above code takes in rows from an excel sheet with 3 values and creates a page with said values, currently I am just trying to get the pdf to work before i go and use jsPDF to create multiple pages. Thanks for advance in any help.
I changed the source of jsPDF as it was done in this question, it seems to have worked:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<!-- <script src="https://unpkg.com/jspdf#latest/dist/jspdf.umd.min.js"></script> --> <!-- --##### REMOVED -->
<script src="http://mrrio.github.io/jsPDF/dist/jspdf.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
type="text/javascript"
src="/js/lib/dummy.js"
></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style id="compiled-css" type="text/css">
img {
width: 100px;
height: 50px;
}
/* EOS */
</style>
<script id="insert"></script>
</head>
<body>
<head>
<style>
#CHARSET "UTF-8";
.page-break {
page-break-after: always;
page-break-inside: avoid;
clear:both;
}
.page-break-before {
page-break-before: always;
page-break-inside: avoid;
clear:both;
}
#html-2-pdfwrapper{
position: absolute;
left: 20px;
top: 50px;
bottom: 0;
overflow: auto;
width: 600px;
}
</style>
</head>
<body>
<button onclick="generate()">Generate PDF</button>
<div id="html-2-pdfwrapper">
<h3 class= "first_header-txt">
Net Weight (KG/LB)
</h3>
<h3 class="first-txt">
Temp1
</h3>
<h3 class= "second_header-txt">
Gross Weight (KG/LB)
</h3>
<h3 class="second-txt">
Temp2
</h3>
<h3 class="details">
Temp3
</h3>
<div>
</body>
<script>
//window.jsPDF = window.jspdf.jsPDF --##### REMOVED
var base64Img = null;
margins = {
top: 70,
bottom: 40,
left: 30,
width: 550
};
generate = function()
{
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.setFontSize(18);
//pdf.html(document.getElementById('html-2-pdfwrapper'), --##### REMOVED
pdf.fromHTML(document.getElementById('html-2-pdfwrapper'),
{
'x' : margins.left, // x coord
'y' : margins.top,
'width' : margins.width,// max width of content on PDF
'callback' : function(pdf) {
pdf.save('NetWeight.pdf');
}
});
var iframe = document.createElement('iframe');
iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:650px; padding:20px;');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
};
</script>
<script>
var ExcelToJSON = function() {
this.parseExcel = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function(sheetName) {
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
var obj = JSON.parse(json_object);
var length = obj.length;
for (var i = 0; i < length; i++) {
var netWeight = obj[i]["netWeight"];
var grossWeight = obj[i]["grossWeight"];
var details = obj[i]["details"];
chumpage(netWeight, grossWeight, details);
}
})
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
function chumpage(netWeight, grossWeight, details) {
var netWeight = netWeight;
var grossWeight = grossWeight;
var details = details;
var netWeightKG = Math.trunc(grossWeight * 2.2);
var grossWeightKG = Math.trunc(grossWeight * 2.2);
chump = document.getElementsByClassName("first-txt");
chump2 = document.getElementsByClassName("second-txt");
chump3 = document.getElementsByClassName("details");
chump[0].style.fontSize = "100px";
chump2[0].style.fontSize = "100px";
chump3[0].style.fontSize = "50px";
for (var i = 0; i < chump.length; i++) {
chump[i].innerText = netWeight + '/' + netWeightKG;
chump2[i].innerText = grossWeight + '/' + grossWeightKG;
chump3[i].innerText = details;
}
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
}
</script>
<form enctype="multipart/form-data">
<input id="upload" type=file name="files[]">
</form>
<script>
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
</script>

Selectable() Jquery mobile alternative

I was looking for the solution for my API but I couldn't find.. All examples or advices didn't work. Could somebody help me out? Or give me any suggestion? I'm still studying JQuery, so any help would be more than welcome..
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New api</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main>
<section>
<div id="alert"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<ul id="wordblock">
</ul>
<div id="result">Result</div>
</section>
<script src="./api.js"></script>
</main>
</body>
</html>
JQuery code:
function screenResolutionAlert(x) {
if (x.matches) {
$("#alert").html("This API doesn't work with touchpads <br> (mobiles, tablets etc) <br> please use computer or laptop with a mouse").show();
} else {
$("#alert").hide();
}
}
var x = window.matchMedia("(max-width: 1200px)")
screenResolutionAlert(x)
x.addListener(screenResolutionAlert)
//API swap words code
$(function () {
$("#wordblock").sortable();
$("#wordblock").disableSelection();
const array = ["pierogi", "gołąbki", "pies", "sześcian"];
const word = array[Math.floor(Math.random() * array.length)];
let d_word = word.split('');
shuffle(d_word);
const lis = [];
for (let i = 0; i < d_word.length; i++) {
lis.push('<li class="ui-state-default">' + d_word[i] + '</li>')
}
$('#wordblock').html(lis.join(''));
$('#wordblock').mouseup(function () {
setTimeout(() => {
let r_word = '';
$('#wordblock>li').each(function (e) {
r_word += $(this).text();
});
if (r_word == word) {
$("#result").html(`Correct! It was exactly "${r_word}"`);
} else {
$("#result").html(`Wrong! keep trying.. <br> it's not "${r_word}"`);
}
}, 0);
});
});
function shuffle(a, b, c, d) {
c = a.length;
while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d
}
Yes I was using mobile Jquery links, didn't work... And any versions of.. I tried everything what was written in the internet ;(
I tried your code and ...it seems to work! Snippet is here below, just press Run code snippet, and order letters to "PIES".
I suggest you to read about APIs, because at the moment you're not using any API at all! 😁
function screenResolutionAlert(x) {
if (x.matches) {
$("#alert")
.html(
"This API doesn't work with touchpads <br> (mobiles, tablets etc) <br> please use computer or laptop with a mouse"
)
.show();
} else {
$("#alert").hide();
}
}
var x = window.matchMedia("(max-width: 1200px)");
screenResolutionAlert(x);
x.addListener(screenResolutionAlert);
//API swap words code
$(function () {
$("#wordblock").sortable();
$("#wordblock").disableSelection();
const array = ["pies"];
const word = array[Math.floor(Math.random() * array.length)];
let d_word = word.split("");
shuffle(d_word);
const lis = [];
for (let i = 0; i < d_word.length; i++) {
lis.push('<li class="ui-state-default">' + d_word[i] + "</li>");
}
$("#wordblock").html(lis.join(""));
$("#wordblock").mouseup(function () {
setTimeout(() => {
let r_word = "";
$("#wordblock>li").each(function (e) {
r_word += $(this).text();
});
if (r_word == word) {
$("#result").html(`Correct! It was exactly "${r_word}"`);
} else {
$("#result").html(`Wrong! keep trying.. <br> it's not "${r_word}"`);
}
}, 0);
});
});
function shuffle(a, b, c, d) {
c = a.length;
while (c)
(b = (Math.random() * (--c + 1)) | 0),
(d = a[c]),
(a[c] = a[b]),
(a[b] = d);
}
ul#wordblock {
padding-left: 0;
}
ul#wordblock li {
display: inline-block;
font-size: 2em;
padding: 0.2em 0.2em;
cursor: pointer;
background-color: aliceblue;
border-radius: 50%;
margin: 0.5em;
width: 1em;
height: 1em;
text-align: center;
line-height: 0.9em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New api</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main>
<section>
<div id="alert"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<ul id="wordblock">
</ul>
<div id="result">Result</div>
</section>
<script src="./api.js"></script>
</main>
</body>
</html>

How to build array contains conditional

I need to build a window listener that triggers on the mouseover on a box using contains and I'm not quite sure of how to build that?
This is a test I've built:
window.addEventListener("mouseover", trial)
function trial(e) {
const contain_material = document.getElementsByClassName("item")
if(contain_material.contains(e.target)) {
alert("so far so good")
}
else {
return
}
}
See if the following works for you.
function trial(e) {
const contain_material = document.getElementsByClassName("item")
for (var i = 0; i < contain_material.length; i++) {
if(contain_material[i] == e.target) {
alert("so far so good")
}
}
}
Instead of checking hover on the window, why not just check when one of those elements is hovered over. For example:
const contain_material = document.getElementsByClassName("item")
for (mat of contain_material) {
mat.addEventListener("mouseover", trial)
}
function trial(e) {
alert("so far so good")
}
Can't you just listen to the mouseover on the box element instead of in the whole page?
function handleMouseOver() {
alert('so far so good')
}
// or you can add dynamicaly with js
var boxes = document.getElementsByClassName("item");
Array.from(boxes).forEach(function() {
this.onmouseover = () => alert('so far so good')
})
// () => this is an arrow function in case you dont know
// Array.from() is because you can't use the forEach straight with a HTMLCollection
body {
display: flex;
}
.item {
width: 300px;
height: 300px;
background-color: yellow;
margin: 10px;
}
<!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>
</head>
<body>
<div class="item" onmouseover="handleMouseOver()"></div>
<div class="item" onmouseover="handleMouseOver()"></div>
<div class="item" onmouseover="handleMouseOver()"></div>
<div class="item" onmouseover="handleMouseOver()"></div>
</body>
</html>

Categories

Resources