Display text after mouseover on image using Ajax - javascript

I have written this Code in order to display the information after mouseover an Image. There are three images on the website, and each Image have the own text information:
var resOb = new XMLHttpsRequest ();
window.onload = function() {
document.getElementsByTagName("img").onmouseover =
function sndReq(0) {
}
document.getElementsByTagName("img").onmouseover =
function sndReq(1) {
}
document.getElementsByTagName("img").onmouseover =
function sndReq(2) {
}
}
function sndReq(i) {
switch (i) {
case 0:
resOb.open('get', 'info0.txt', true);
break;
case 1:
resOb.open('get', 'info1.txt', true);
break;
case 2:
resOb.open('get', 'info2.txt', true);
break;
resOb.onreadystatechange = function() {
handleResponse(i);
}
}
function handleResponse () {
document.getElementById("info0").innerHTML =
resOb.responseText;
}
Sadly it doesn't work, and I'm not able to find out where the problem is. I need some help.
Here the HTML Output
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>AJAX</title>
<meta name="viewport" content=
"width=device-width; initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="lib/css/stil.css" />
<script type="text/javascript"
src="lib/js/ajaxeinsendeaufgabe2.js"></script>
</head>
<body>
<h1>Zusatzinformationen</h1>
<table>
<tr>
<td><img class="img" src="img/b1.jpg" data-file="info0" /></td>
<td id="info0"></td>
</tr>
<tr>
<td><img class="img" src="img/b2.jpg" /></td>
<td id="info1"></td>
</tr>
<tr>
<td><img class="img" src="img/b3.jpg" /></td>
<td id="info2"></td>
</tr>
</table>
</body>
</html>

Your handle response does not use i it has hard coded "info0". It should be:
function handleResponse (i) {
document.getElementById("info"+i).innerHTML =
resOb.responseText;
}
also you do not need a switch case you can do the same with:
resOb.open('get','info'+i+'.txt',true);
here is a link to the refactor fiddle https://jsfiddle.net/pyr2447k/6/
try to see if that one will work.

Related

addEventlistener for buttons does not work properly with more than one button

I want to create a script where I can upload files via event listener drop.
Everytime a file is dropped, a new table row has to be created with a save/edit button. These buttons need event listeners for click, but the problem is that the event listener works only on the last button added to the table.
I have made a simplified example of my problem. The function clickEventSaveButton() contains an .addEventlistener, with an anonymous function. For now it just executes a console log, but only for the button in the last table row. Everytime a new button is created, the old one stops working.
JS:
'use strict';
const dragArea = document.getElementById('dragArea');
const fileTable = document.getElementById('fileTable');
const fileTableBody = fileTable.querySelector('tbody');
let id = 0;
dragArea.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
});
dragArea.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
// Add table row
fileTableBody.innerHTML += createFileTableRow(id, 'placeholder');
clickEventSaveButton(id);
id++;
});
function clickEventSaveButton(id) {
let saveButton = document.querySelector('.file-save a[data-id="'+id+'"]');
console.log(saveButton);
console.log(id);
saveButton.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
console.log('Save Button (ID:'+id+') pressed!');
});
}
function createFileTableRow(id, name) {
return `
<tr data-id="${id}">
<td class="file-name">${name}</td>
<td class="file-save">
<a data-id="${id}" class="button is-info is-small">Save</a>
</td>
</tr>
`;
};
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'self';">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.1/css/bulma.min.css">
<script defer src="test.js"></script>
</head>
<body>
<div class="columns"><div class="column is-half is-offset-one-quarter">
<h1>Work in progress</h1>
<div id="dragArea" class="box has-background-info-light has-text-centered py-6">
Drag .xlsx files here!
</div>
<hr>
<h3 id="fileTableTitle">No files loaded...</h3>
<table id="fileTable" class="table table is-fullwidth is-hoverable">
<thead><tr><th>File</th><th>Save File</th></tr></thead>
<tbody></tbody>
</table>
<hr>
</div></div>
</body>
</html>
So, thanks to Patrick Evans I was able to solve the issue that bugged me for some hours.
Instead of innerHTML I have to use insertAdjacentHTML.
Solution:
fileTableBody.insertAdjacentHTML('beforeend', createFileTableRow(id, 'placeholder'));

Capturing href and prevent event default

Not sure why the code is not working. The javascript is not printing the alert box nor preventing the event default. I was under the assumption that the data would load asynchronously keeping me on the same page.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<div data-role="page">
<div data-role="header"></div>
<div data-role="content">
<p id = "heading">Is Nursing For You?</p>
<br/>
<div id = "div1" align="center"></div>
</div>
<div data-role="footer" id = "foot" data-position="fixed">
<table>
<tr>
<th><h1 id = "alignLeft">Future Goals</th></h1>
<th><h1 id = "socialMediaText alignCenter">Get Social With Us!</h1>
</th>
<th></th>
</tr>
<tr>
<td id = "alignLeft">Telephone: 304-444-39876</td>
<tr>
<td = "alignLeft">Email: futurenurseky#gmail.com</td>
</tr>
</tr>
</table>
</div>
</div>
This is where im having the trouble at. Not sure why the alert is not sending or redirecting me.
<script type='text/javascript'>
$(document).ready(function(){
$("#div1").load("FONWVhp.php");
$('#div1').click(function(e){
e.preventDefault();
alert($(this).attr('href'));
});
});
</script>
</body>
</html>
This is the Fp.php which is called when the page is loaded but once the page is loaded there are href's that are displayed. so when the person clicks the href the page will stay but the data will change and get the info coming from articles.php (at the bottom).
$sqlPAQuery = "SELECT pages.pageId, pages.pageTitle FROM pages order by
pages.pageId";
$paqueryResult = mysqli_query($conn,$sqlPAQuery);
while ($paqueryRow = mysqli_fetch_object($paqueryResult))
{
$pages = "<div class='center-wrapper'><a href = articles.php?
pageId=".$paqueryRow->pageId."><button class= center-wrapper'>".$paqueryRow-
>pageTitle."</button></a><br/><br/></div>";
echo $pages;
}
articles.php
$sqlARTICLEQuery = "SELECT * FROM articles where pageId=".$_GET['pageId']."
order by articleId";
$articlequeryResult = mysqli_query($conn,$sqlARTICLEQuery);
while ($articlequeryRow = mysqli_fetch_object($articlequeryResult))
{
$articles ="<div id = 'div1' class='center-wrapper'><a href =
article.php?articleId=".$articlequeryRow->articleId."><button id
='wrapper'>".$articlequeryRow->articleTitle."</button></a><br/><br/></div>";
echo $articles;
}
You need to wait for the div contents to load before manipulating it. Try this:
$(document).ready(function() {
$("#div1").load('FONWVhp.php', function() {
$('#div1 div.center-wrapper a button').click(function(event){
event.preventDefault();
alert($(this).parent().attr('href'));
});
});
});
Also, I've corrected some mistakes in your code:
Instead of $('#div1').click(...) use $('#div1 div.center-wrapper a button').click(...).
I suppose you want the anchor's href, so you need to use alert($(this).parent().attr('href')).
just put an e / event in the function
<script type='text/javascript'>
$(document).ready(function(){
$("#div1").load("Fp.php");
$('div.div1 a button').click(function(e){
e.preventDefault();
alert($(this).attr('href'));
});
});
</script>

Javascript function not recognized in HTML

I'm trying to call a java script function on my mouse over function for an image, however; the debugger says "function isn't defined." I don't understand why I'm getting this error. The java script and tags look to be correct and it seems like I'm using the correct syntax to call the function.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Chapter11-1</title>
<script type="text/javascipt">
function overButton(img) {
buttonImg="chapter11-1"+img+"_over.gif"
document.getElementById(img).src=buttonImg
}
function downButton(img) {
buttonImg="chapter11-1"+img+"_down.gif"
document.getElementById(img).src=buttonImg
}
function upButton(img) {
buttonImg="chapter11-1"+img+"_up.gif"
document.getElementById(img).src=buttonImg
}
</script>
</head>
<body>
<div id="banner_logo"><img src="chapter11-1banner.jpg" width="745" height="150" alt="banner" id="banner" /></div>
<table class="centerItems">
<tr>
<td>
<a href="#">
<img src="chapter11-1home_up.gif" id="home" alt="home" onMouseOver="overButton('home')" onMouseDown="downButton('home')" onMouseOut="upButton('home')" onMouseUp="upButton('home')" /></a>
</td>
</body>
</html>
It doesn't work because you spelled "javascript" wrong.
Change this
<script type="text/javascipt">
to
<script type="text/javascript">
or just
<script>
Otherwise it's assumed that the script tag is something other than javascript
And use lowercase for the events, preferably you'd use addEventListener
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Chapter11-1</title>
</head>
<body>
<div id="banner_logo"><img src="chapter11-1banner.jpg" width="745" height="150" alt="banner" id="banner" /></div>
<table class="centerItems">
<tr>
<td>
<a href="#">
<img src="chapter11-1home_up.gif" id="home" alt="home" onMouseOver="overButton('home')" onMouseDown="downButton('home')" onMouseOut="upButton('home')" onMouseUp="upButton('home')" /></a>
</td>
</tr>
</table>
</body>
<script>
function overButton(img) {
buttonImg="chapter11-1"+img+"_over.gif";
document.getElementById(img).src=buttonImg;
}
function downButton(img) {
buttonImg="chapter11-1"+img+"_down.gif";
document.getElementById(img).src=buttonImg;
}
function upButton(img) {
buttonImg="chapter11-1"+img+"_up.gif";
document.getElementById(img).src=buttonImg;
}
</script>
</html>

how can i randomly select a cell in my TIC TAC TOE

I am new to programming as to stack overflow so be easy on me. i am making an tic tac toe game and haven't found a to mark a random_cell and append and image to it so if you could help it will be of most help. jquery are also welcome
var x_or_o = ["x","o"];
var user = x_or_o[Math.floor(Math.random()*x_or_o.length)];
function random_cell(){
var cells = ["zero","one","two"];
return ("#"+cell[Math.floor(Math.random()*cells.length)]+"_"+cell[Math.floor(Math.random()*cells.length)]);
}
function clink(id_ele){
$(id_ele).one(("click",water(id_ele)));
}
function water(id_ele){
$(id_ele).click(function(){
if (user == "x"){
$(id_ele).append("<img src =img/x.png>").addClass("done-x");
if (! random_cell.hasClass()){
$(random_cell).append("<img src =img/o.png>");
}
else{
random_cell();
water(id_ele);
}
}
else if (user == "o"){
$(id_ele).append("<img src =img/o.png>").addClass("done-o");
}
}
)
}
clink("#zero_zero");
clink("#zero_one");
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tic Tac Toe</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<header>
<h1>TIC TAC TOE</h1>
</header>
<section>
<table>
<tr>
<td id = "zero_zero"></td>
<td id = "one_zero"></td>
<td id = "two_zero"></td>
</tr>
<tr>
<td id = "zero_one"></td>
<td id = "one_one"></td>
<td id = "one_two"></td>
</tr>
<tr>
<td id = "two_zero"></td>
<td id = "two_one"></td>
<td id = "two_two"></td>
</tr>
</table>
</section>
<footer>
<p>© Kunal Mehta 2016</p>
<img src="img/facebook.png" alt="">
<img src="img/twitter.png" alt="">
</footer>
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
</body>
</html>
You can simply use Math.random() to create numbers and then build a little translation for your ids, as you did. But note that your current ids makes no sense. They're inconsistent. I've changed them a bit to be usefull.
Also note, that your array in random_cell is called cells, but in your random creation you uses cell. This will not work too.
function random_cell() {
var cells = ["zero","one","two"];
var length = cells.length;
return ("#" + cells[Math.floor(Math.random()*length)] +
"_" + cells[Math.floor(Math.random()*length)]);
}
setInterval(function() {
var id = random_cell();
$("td").removeClass("highlight");
$(id).addClass("highlight")
}, 500);
.highlight {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="zero_zero">1</td>
<td id="one_zero">2</td>
<td id="two_zero">3</td>
</tr>
<tr>
<td id="zero_one">4</td>
<td id="one_one">5</td>
<td id="two_one">6</td>
</tr>
<tr>
<td id="zero_two">7</td>
<td id="one_two">8</td>
<td id="two_two">9</td>
</tr>
</table>
Your random_cell function does the following:
return ("onecell");
Thats wrong syntax. Do:
return "onecell";
The next mistake:
$(random_cell).append(...);
Random_cell is not a Variable !!! Its a function. Do:
$( random_cell() ).append(...);
Mistake No.3:
The clink function adds an eventlistener that adds an eventlistener. So you have to click it twice to make it work...
Mistake No.4
<img src=img.jpg >
Thats wrong HTML. Do:
<img src='img.jpg'>

CKEditor option startupMode causes js error

I was trying to find out what is wrong with this code for a few hours. After double-clicking on divs CKEditor correctly opens and after pressing down the button it correctly hides. But after clicking again on div it doesn't want to open again and then firebug returns an error "p is null" in line 86 in ckeditor.js.
Finally it turned out that the problem disappears when I turn off the option "startupMode: 'source'". Has anyone an idea what this behaviour is caused by? Is it a bug in CKEditor or I do something wrong.
Version of CKEditor I use is 3.6.4.
Thanks in advance for any help!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/admin/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
</head>
<body>
<h2>Vars</h2>
<table>
<tbody>
<tr>
<td>Cell no 1.1</td>
<td><div class="editable" id="cell1">Cell no 1.2</div></td>
</tr>
<tr>
<td>Cell no 2.1</td>
<td><div class="editable" id="cell2">Cell no 2.2</div></td>
</tr>
</tbody>
</table>
<input type="submit" id="submit" value="Close"/>
<script type="text/javascript">
editor = false;
function destroy_cke() {
if (editor) {
editor.updateElement();
editor.destroy();
}
}
function replace_div(div) {
destroy_cke();
editor = CKEDITOR.replace(div,{
startupMode: 'source',
});
}
$(document).ready (function() {
$('.editable').dblclick(function(e) {
e.stopPropagation();
var element = e.target || e.srcElement;
while (element.nodeName.toLowerCase() != 'html' && (element.nodeName.toLowerCase() != 'div' || element.className.indexOf('editable') == -1 )) element = element.parentNode;
replace_div(element);
});
$('#submit').click(function(){
destroy_cke();
});
});
</script>
</body>
</html>
Answered at http://cksource.com/forums/viewtopic.php?f=11&t=26734&p=67792#p67792
The destroy_cke function isn't clearing the editor variable.

Categories