Compare data attributes of dynamically created elements with JQuery - javascript

I'm making a game where after you click an image it will shuffle the array and repopulate the DOM. The idea is that you can't click the same image twice even though the images in the array are shuffled.
HTML
<!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">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Document</title>
</head>
<body>
<!-- Tribute to Tom Whalen for the awesome Transformers pictures -->
<button id="shuffleButton" type="submit">Shuffle</button>
<div id="test"></div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="app.js">
</script>
</body>
</html>
The #testDiv is populated on page load and each time you click it shuffles the array and repopulates #testDiv.
Each image in the object has a name property related to the character's image.
I'm using Transformers.
Here's an example from the array of objects I am using.
var images = [
{
name: "bumblebee",
image: "assets/images/bumblebee.jpg"
},
{
name: "frenzy",
image: "assets/images/frenzy.jpg"
}];
JavaScript
/*Working for loop through images array */
function loop() {
for (var i =0; i < images.length; i++) {
var testImage = $('<img class="images">')
.attr('src', `${images[i].image}`)
.attr('data', `${images[i].name}`);
$(testDiv).append(testImage);
};
};
loop();
function Shuffle() {
images.sort(function(a, b) {
return 0.5 - Math.random()
});
loop();
};
$("#shuffleButton").on('click', function(){
$(testDiv).empty();
Shuffle();
console.log(images);
});
var count = 0;
$(document).on('click', '.images', function() {
$(testDiv).empty();
Shuffle();
console.log($(this).data());
});
I am assigning the name property to a data attribute and want to compare the data attributes with a click function.
When I console.log($(this).data()); I get a blank object with ___proto___ : Object and not the data attribute.
How would I grab the data attribute?
How woinI then store that into a variable?
How would I compare that data attribute inside of a variable to another element's data attribute?

You will need to send the data attributes name for your console.log function.
console.log($(this).data('name'));
I have attached an example below.
$(document).on('click', '#div', function() {
alert($(this).data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div" data-id="test" >hello</div>

Related

when i try to access array element by index it gives me undefined

i created an array and insert elements by array.push(). when i console.log(array) it gives me following out put output of console.log(array)
when i console.log(array[0]) it gives me undefined. why is happing and a blue i tag appear in picture which says "this value was evaluated on first expanding it may have changed since then in array javascript" what does means. please help me to understand the problem
here the full code
index.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>zip reader</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/jstree.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<body>
<h3>Choose the local(s) zip file(s)</h3>
<input type="file" id="file" name="file" multiple /><br />
<div id="result_block" class="hidden">
<h3>Content :</h3>
<div id="result">
</div>
</div>
</body>
<script src="jszip.min.js"></script>
<script src="jszip-utils.min.js"></script>
<script src="app1.js"></script>
<script src="FileSaver.min.js"></script>
</html>
app1.js =>
var array = []
var contents = []
var $result = $("#result");
$("#file").on("change", function(evt) {
// remove content
$result.html("");
// be sure to show the results
$("#result_block").removeClass("hidden").addClass("show");
// Closure to capture the file information.
function handleFile(f) {
var $title = $("<h4>", {
text : f.name
});
var $fileContent = $("<ul>");
$result.append($title);
$result.append($fileContent);
var dateBefore = new Date();
JSZip.loadAsync(f) // 1) read the Blob
.then(function(zip) {
var dateAfter = new Date();
$title.append($("<span>", {
"class": "small",
text:" (loaded in " + (dateAfter - dateBefore) + "ms)"
}));
zip.forEach( function (relativePath, zipEntry) {
var y = zipEntry.name
array.push(y);
$fileContent.append($("<li>", {
text : zipEntry.name
}));
});
}, function (e) {
$result.append($("<div>", {
"class" : "alert alert-danger",
text : "Error reading " + f.name + ": " + e.message
}));
});
}
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
handleFile(files[i]);
}
console.log(array[0])
});
When you console.log an object (including arrays), it isn't being serialized, and only a reference is passed to a console. When you expand it, this reference is used to check the state of this object.
Most probably what's happening is the following sequence:
console.log(array) // passes array reference to a console
console.log(array[0]) // prints undefined immediately
array.push(...) // an actual array modification
you expand the object, and console checks the content of an array
PS.
It's reasonable to ask, what will happen, if the reference will become invalid due to any reason.
For browsers - it's simpler, since the console and JS program run under same parent process, browser is responsible for everything.
But if you'll ever try to debug Node process, which has the same API of passing the reference, you will face strange issues all over around, like this one: No debug adapter, can not send 'variables VSCODE

I am not sure I can access the second html file using one js file, html element is showing as null when it is a button

I have 2 html files connected to one js file. When I try to access a html element in the second html file using js it doesn't work saying that is is null. I did
let elementname = document.getElementById("element") for a element in the second html page then
console.log(elementname) and it says it is null. When I do it for a element in the first html page it says HTMLButtonElement {}
Here is the html for the first Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Not Quuuuiiiizzzz</h1>
<h2>Join a quiz</h2>
<!--Buttons -->
<div style="text-align: center;">
<button id="btnforquiz1" onclick="gotoquiz()"></button>
<button id="btnforquiz2" onclick="gotoquiz1()"></button>
<button id="btnforquiz3" onclick="gotoquiz2()"></button>
</div>
<h2 id="h2">Create a Quuuuiiiizzzz</h2>
<script src="script.js"></script>
</body>
</html>
For the second page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body onload="quizLoad()">
<h1 id="question">Hello</h1>
<button id="answer1"></button>
<button id="answer2"></button>
<button id="answer3"></button>
<button id="answer4"></button>
<script src="script.js"></script>
</body>
</html>
And Finally for the js file :
//setting global variables
let btn1 = document.getElementById("btnforquiz1") //getting button with id of btnforquiz1 repeat below
correct = 0
let btn2 = document.getElementById("btnforquiz2")
let btn3 = document.getElementById("btnforquiz3")
let question = document.getElementById("question")
let answer1 = document.getElementById("answer1")
let answer2 = document.getElementById("answer2")
let answer3 = document.getElementById("answer3")
let answer4 = document.getElementById("answer4")
quizNameRel = -1;
cosnole.log(question)
console.log(answer1)
//Quiz Data
Quiz_1 = {
"What is the capital of buffalo":["Idk", "Yes", "No",0],
"What is the smell of poop": ["Stinky"]
};
Quiz_2 = [
"What is wrong with you"
];
Quiz_3 = [
"What is wrong with you #2"
]
let quiz = {
name: ["History Test", "Math Practice", "ELA Practice"],
mappingtoans: [0,1,2],
QA: [Quiz_1, Quiz_2, Quiz_3]
}
//quiz data
//when body loades run showQuizzs function
document.body.onload = showQuizzs()
function showQuizzs() {
//loops throo the vals seeting the text for the btns
for (let i = 0; i < quiz.name.length; i++) {
btn1.textContent = quiz.name[i-2]
btn2.textContent = quiz.name[i-1]
btn3.textContent = quiz.name[i]
}
}
//leads to the showQuizzs
function gotoquiz() {
location.href = "quiz.html"
quizNameRel = quiz.name[0]//I was trying to create a relation so we could knoe which quiz they wnt to do
startQuiz()
}
function gotoquiz1() {
location.href = "quiz.html"
quizNameRel = quiz.name[1]
startQuiz()
}
function gotoquiz2() {
location.href = "quiz.html";
quizNameRel = quiz.name[2];
startQuiz();
}
function answerselect(elements){
whichone = Number(elements.id.slice(-2,-1))
if(Quiz_1[whichone]==Quiz_1[-1]){
correct+=1;
NextQuestion();
}else{
wrong+=1;
}
}
//gets the keys and puts it into an array
function getkeys(dictionary){
tempdict = [];
for(i in dictionary){
tempdict.push(i);
}
return tempdict;
}
function setQuestion() {
let tempdict = getkeys(Quiz_1)
console.log(tempdict, getkeys(Quiz_1));
//question.innerHTML = tempdict;
}
// startQuiz
function startQuiz() {
switch (quizNameRel){
case quiz.name[0]:
//case here
setQuestion()
break
case quiz.name[1]:
//case here
break
case quiz.name[2]:
//case here
break
}
}
//TO DO:
// Set the question
// Set the answer
// Check if correct button
This is happening because at a time you have rendered only one html file. For example if you render index1.html(first file) then your js will look for rendered element from first file only but here index2.html(second file) is not rendered so your js script is unable to find elements of that file that's the reason it shows null.
If you try to render now index2.html rather than index1.html then you will find now elements from index2.html are detected by js script but elements from index1.html are null now.

Ask about jquery function operation [duplicate]

This question already has answers here:
How to prevent a click on a '#' link from jumping to top of page?
(24 answers)
Closed 2 years ago.
I'm student and it hasn't been long since I studied programming.
below code is simplified than real for explain.
'test()' is actually Ajax function to get data.
My goal is making 'a tag' for paging operation.
But when i clicked 'a tag', 'test()' inside of '$(document).ready' is called after 'a tag' click event occurred.
So page is always back to 1.
I don't know why this happen.
Anyone could help me?
Thank you!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
var page = 1;
$(document).ready(function(){
test();
alert(page);
});
function test(){
for(var i = 1; i <= 3; i++) {
var a = $("<a></a>").text(i).attr({
href: "",
idx: i
});
a.preventDefault;
$(a).click(function(){
page = $(this).attr("idx");
test();
alert(page);
});
$("#pageLink").append(a," ");
}
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>
For some reason you're calling test() inside of test(). There are a few minor things you need to change also
Prefix jQuery objects with $. var $a=... to avoid ambiguity.
preventDefault is used on the event, not the jQuery object. $a.click(function(event){event.preventDefault();...});
Otherwise it works as I believe you want it to, alerting the page number on click.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
createLinks();
});
function createLinks(){
for(var i = 1; i <= 3; i++) {
var $a = $("<a></a>").text(i).attr({
href: "",
idx: i
});
$a.click(function(event){
event.preventDefault();
page = $(this).attr("idx");
// why are you calling this again? // test();
// maybe you want to load something // loadSomething(page);
alert(page);
});
$("#pageLink").append($a," ");
}
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>

How to append the HTML code snippet to HTML iframe using jquery?

How to append the HTML code snippet to HTML iframe using jquery? Actually, I have added an HTML code snippet in MySQL Database using PHP. Now I have fetched that HTML Code snippet and trying to append that HTML code snippet in iframe using jquery.
$( document ).ready(function() {
var snippets='<?php echo $snippets_preview; ?>';
$(function() {
var $iframe = $('#iframehtml');
$iframe.ready(function() {
$iframe.contents().find("body").append(snippets);
});
});
});
But I am getting the following error
Uncaught SyntaxError: Invalid or unexpected token
snippets_preview has the following value in it. when I change the value of snippet_preview. it works fine.
<!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 href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>'.$postdata['snippets_css'].'</style>
<script>'.$postdata['snippets_javascript'].'</script>
</head>
<body>
'.$ContentDecodedHTML.'
</body>
</html>
If you want to embed html code in an iframe you have to do for example:
JAVASCRIPT (class)
<script>
// -------------------------------------------------------- CLASS
var class_iframe = {
// ------------------------------------- STEP 1 (Create an new Iframe)
generateIframe: function(src, targetDOM){
// ---------------- Create iframe
var newIframe = document.createElement('iframe');
newIframe.onload = function(){
class_iframe.getIframe($('.iframehtml').contents());
};
newIframe.src = src;
newIframe.className = "iframehtml";
newIframe.frameBorder = "0";
// ---------------- Insert iframe in DOM
$(targetDOM).replaceWith(newIframe);
},
// ------------------------------------- STEP 2 (Get iframe in this class)
getIframe: function(iframe){
class_iframe.frame = iframe; console.log(class_iframe.frame);
},
// ------------------------------------- STEP 3 (Append in this iframe)
appendIframe: function(targetInIframe, content){
console.log(class_iframe.frame);
$target = class_iframe.frame.find(targetInIframe); console.log($target);
$target.prepend(content);
},
}
// -------------------------------------------------------- ACTION (loadPage)
$(document).ready(function(){
//$("body").prepend(`<div id="insertIframe"></div>`); //Just for the test
class_iframe.generateIframe("your_url_iframe.html", "#insertIframe");
});
</script>
In your html page
<div id="insertIframe"></div>
JAVASCRIPT (for append in your new iframe)
<script>
// -------------------------------------------------------- ACTION (after loadPage)
class_iframe.appendIframe("html", `<div class="insert">Hello world !</div>`);
</script>

Can't get javascript to change img source

A real beginner here, with a really basic question, but I simply can't get Javascript to change pictures when using the build in "onclick()" with HTML images..
I looked through so many questions about this, and tried different approaches to changing it, but can't get it to work.
I've tried with different src's, providing the full path and with online image adresses. Tried passing the variable. Simply can't get it to work.
<head>
<meta charset="utf-8">
<title> Javascript - changing images </title>
<script type="text/javascript">
function change() {
var image = document.getElementByID("fpimage");
image.src = "logo2.png"
}
</script>
</head>
<body>
<img src="logo.png" alt = "bla" id = "fpimage" onclick="change();"">
</body>
</html>
Change
var image = document.getElementByID("fpimage");
TO
var image = document.getElementById("fpimage");
You misspelled getElementById with a capital D
<head>
<meta charset="utf-8">
<title> Javascript - changing images </title>
<script type="text/javascript">
function change() {
var image = document.getElementById("fpimage");
image.src = "logo2.png"
}
</script>
</head>
<body>
<img src="http://i.imgur.com/cJjyJaG.jpg" alt = "bla" id = "fpimage" onclick="change();"">
</body>
</html>
Yep, like Clyde said, you made a mistake on the getElementById() function, keep in mind that Js is case sensitive ;)
<head>
<meta charset="utf-8">
<title> Javascript - changing images </title>
<script type="text/javascript">
function change() {
var image = document.getElementById("fpimage");
image.src = "http://www.dinosoria.com/mammifere/paresseux-206.jpg"
}
</script>
</head>
<body>
<img src="http://s.minutebuzz.com/i/2014/05/sloths-L.jpg.jpg" alt = "bla" id = "fpimage" onclick="change();"">
</body>
</html>

Categories