jQuery load breaks function - javascript

My PHP webpage page1.php is like this:
<html>
<head>
<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
function ciao(){
$('#files').load('page2.php?SQL_type=files');
}
$(function(){
$(".icon_files").bind("contextmenu",function(e){
var left;
var top;
if($(document).width() < 630){
left = 0;
top = 0;
}else{
left = e.pageX;
top = e.pageY;
}
$("#context").css({left: left, top: top});
contextmenu($(this).attr('id'));
e.preventDefault();
});
});
</script>
</head>
<body>
<button onclick="ciao()">ciao</button>
<div id="files">
<?php
$_GET['SQL_type'] = 'files';
include "page2.php";
?>
</div>
</body>
</html>
I've build a custom contextmenu that appears with the code above.
When the page loads and include page2.php through PHP it works, but when I change #files content via jQuery, the contextmenu (and all other function I haven't copied there) no longer works.
I've tried other codes like
jQuery.get('page2.php?SQL_type=files', null, function(data) {
$('#files').append(data);
}, 'html');
And I've tried also with simple Javascript
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("files").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "page2.php?SQL_type=files", true);
xmlhttp.send();
Inside page2.php there are simply some DIVs everyone of them with icon_files as class and it doesn't include jQuery again. It is simply like
<div class="icon_files">something</div><div class="icon_files">other</div>
I don't have any other ideas, what could be the problem here?
Thank you

The jquery code is running, however, the elements the jquery code is targeting are being replaced after clicking the button, thus causing them to lose events/data. Try using event delegation instead. This causes the event to be bound to the id="files" element rather than the elements that are being replaced.
function ciao() {
$('#files').html('<div class="icon_files">another icon...</div>');
}
$(function() {
$("#files").on("contextmenu", ".icon_files", function(e) {
var left;
var top;
if ($(document).width() < 630) {
left = 0;
top = 0;
} else {
left = e.pageX;
top = e.pageY;
}
$("#context").css({
left: left,
top: top
});
console.log('context menu');
e.preventDefault();
});
});
<html>
<head>
<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
</script>
</head>
<body>
<button onclick="ciao()">ciao</button>
<div id="files">
<div class="icon_files">icon...</div>
</div>
</body>
</html>

Related

Embedding multiple pages with same header in multiple <div>

I want to embed url http://localhost:8081/static/bar.html in the main div at my index.html, so I wrote the below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Awesome echarts</title>
<script src="https://go-echarts.github.io/go-echarts-assets/assets/echarts.min.js"></script>
<link href="https://go-echarts.github.io/go-echarts-assets/assets/bulma.min.css" rel="stylesheet">
</head>
<body>
<div id="main">
<object id="foo" name="foo" type="text/html" data="http://localhost:8081/static/bar.html"></object>
</div>
</body>
</html>
Where my bar.html is:
<div class="select" style="margin-right:10px; margin-top:10px; position:fixed; right:10px;"></div>
<div class="container">
<div class="item" id="eeUwxscJvXae"
style="width:900px;height:500px;"></div>
</div>
<script type="text/javascript">
"use strict";
var myChart_eeUwxscJvXae = echarts.init(document.getElementById('eeUwxscJvXae'), "white");
var option_eeUwxscJvXae = {
title: {"text":"Bar-示例图",},
tooltip: {},
legend: {},
toolbox: {"show":true,"feature":{"saveAsImage":{},"dataZoom":{},"dataView":{},"restore":{}}},
xAxis: [{"data":["衬衫","牛仔裤","运动裤","袜子","冲锋衣","羊毛衫"],"splitArea":{"show":false,},"splitLine":{"show":false,}}],
yAxis: [{"axisLabel":{"show":true},"splitArea":{"show":false,},"splitLine":{"show":false,}}],
series: [
{"name":"商家A","type":"bar","data":[43,10,4,12,6,38],"label":{"show":false},"emphasis":{"label":{"show":false},},"markLine":{"label":{"show":false}},"markPoint":{"label":{"show":false}},},
{"name":"商家B","type":"bar","data":[21,44,37,19,32,34],"label":{"show":false},"emphasis":{"label":{"show":false},},"markLine":{"label":{"show":false}},"markPoint":{"label":{"show":false}},},
],
color: ["#c23531","#2f4554","#61a0a8","#d48265","#91c7ae","#749f83","#ca8622","#bda29a","#6e7074","#546570","#c4ccd3"],
};
myChart_eeUwxscJvXae.setOption(option_eeUwxscJvXae);
</script>
<style>
.container {margin-top:30px; display: flex;justify-content: center;align-items: center;}
.item {margin: auto;}
</style>
But While loading it at the browser, I got an error:
Uncaught ReferenceError: echarts is not defined
at bar.html:9
Why this is happening, is not it assumed that sub div are calling the header in the caller file?
I got it resolved by re-wriitng the header in the bar.html file, i.e.:
<head>
<script src="https://go-echarts.github.io/go-echarts-assets/assets/echarts.min.js"></script>
<link href="https://go-echarts.github.io/go-echarts-assets/assets/bulma.min.css" rel="stylesheet">
</head>
But is not this meaning double loading of the echarts.min.js and the bulma.min.css and what if I wanted to embed multiple pages like this, in multiple divs in the index.html do I need to call these files for every single div?
This is an example that I just tested. It works fine, and will suffice for your purpose.
index.html
<html>
<head>
</head>
<body>
<div source="header.html"></div>
<script>
window.test = "this is a test";
function includeSource() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain attribute:*/
file = elmnt.getAttribute("source");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
elmnt.innerHTML = this.responseText;
// now we'll run the js if there is some direct js code in script tags
var html = document.createElement('html');
html.innerHTML = this.responseText;
const scripts = html.getElementsByTagName("script");
for (const script of scripts) {
eval(script.innerText);
}
}
if (this.status == 404) {
elmnt.innerHTML = "Page not found.";
}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("source");
includeSource();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
includeSource();
</script>
</body>
</html>
header.html
<style>
.header {
font-size: 50px;
color: blueviolet;
}
</style>
<div class="header">
<span>Test</span>
<button onclick="console.log(window.test)">click me</button>
</div>
<script>
console.log(window.test);
</script>
Observe the source attribute on the div; it'll be used to define the path of the html file you want to load and you can include your JS and CSS in the same file.

How can I load a header, change it, then redirect to a page with the updated header?

I have 3 html documents: header.html, blackPage.html, and greenPage.html. header.html is common to both blackPage.html and greenPage.html. I want to make it so that a button in the header, used to change pages, reflects the color of the current page using a script called HeaderScript.js. How should I go about doing this? (This is just an example: in the real application, the green page won't have enough info on it to determine what the header should be, so I can't just update it when I load the green page).
Here are the 4 files I'm using:
header.html
<html>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src=HeaderScript.js></script>
<script>
$(document).ready(function(){
$("#Button").click(function(){
changePage($("#Button").get(0));
});
});
</script>
<style>
#Button {
height: 80px;
width: 80px;
background-color: black;
}
</style>
<div id="Button"></div>
</html>
blackPage.html
<html>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#Header").load("header.html");
});
</script>
<Title>Black Page</Title>
<h>Black Page</h>
<div id="Header"></div>
</html>
greenPage.html
<html>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#Header").load("header.html");
});
</script>
<Title>Green Page</Title>
<h>Green Page</h>
<div id="Header"></div>
</html>
HeaderScript.js
function changePage(div){
if (div.style.backgroundColor === "green"){
div.style.backgroundColor = "black";
alert("Color changed to black");
document.location.href = "blackPage.html";
}
else{
div.style.backgroundColor = "green";
alert("Color changed to green");
document.location.href = "greenPage.html";
}
}
New header.html page code:
<html>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
<script src="HeaderScript.js"></script>
<script>
$(document).ready(function(){
var path = window.location.pathname;
path = path.substr(path.lastIndexOf('/') + 1,
path.indexOf('Page.html') - path.lastIndexOf('/') - 1);
$("#Button").css('background-color', path);
$("#Button").click(function(){
path = (path == 'green' ? 'black' : 'green');
$("#Button").css('background-color', path);
window.location = path + 'Page.html';
});
});
</script>
<style>
#Button {
height: 80px;
width: 80px;
}
</style>
<div id="Button"></div>
</html>
Hope that works ;)
Let me know..
ThatWeirdo's answer works, and his answer makes the color load before the page changes (as opposed to this solution), but I need to do it differently for the specific problem for which this question was just an example (my original code was garbage, so I made this example to try to make it simpler/clearer).
Here is what I'm going to end up doing (this assumes blackPage.html is always the first page loaded):
header.html
<html>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src=HeaderScript.js></script>
<script>
$(document).ready(function(){
//--ADDED--
var buttonColor = localStorage.buttonColor;
if(buttonColor !== undefined){
$("#Button").css("background-color", buttonColor);
}
//----
$("#Button").click(function(){
changePage($("#Button").get(0));
});
});
</script>
<style>
#Button {
height: 80px;
width: 80px;
background-color: black;
}
</style>
<div id="Button"></div>
</html>
HeaderScript.js
function changePage(div){
if (localStorage.buttonColor === "green"){ //CHANGED
localStorage.buttonColor = "black"; //CHANGED
alert("Color changed to black");
document.location.href = "blackPage.html";
}
else{
localStorage.buttonColor = "green"; //CHANGED
alert("Color changed to green");
document.location.href = "greenPage.html";
}
}

Reading image filenames from spans

I want to have an Image Slider which reads Image names from spans. What's wrong with my code? Even the alert command not executed. How to fix this?
<html><head>
<title></title>
<script src="Default.aspx_files/jquery-1.js" type="text/x-jquery-tmpl"></script>
<script src="Default.aspx_files/General.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
jQuery(function () {
var i = 0;
var banner = $('.imagesContainer span').map(function () {
return $.trim($(this).text())
}).get();
function fun() {
//How to init array here from inner text of spans?
i++;
if (i == banner.length) {
i = 0;
}
$('#img1').attr('src', '/slide/' + banner[i]);
alert('/slide/' + banner[i]);
}
setInterval(fun, 1000);
})
</script>
</head>
<body>
<form method="post" action="Default.aspx" id="form1">
<div class="imagesContainer">
<span>
73defe4b-9819-4e12-b351-3813686e0c83.gif
</span>
<span>
4c2ed116-500d-42ad-8aa5-983bf214d5d3.png
</span>
</div>
</form>
</body></html>
Its not that you didn't know but it worked on a change of type="text/x-jquery-tmpl" to text/javascript in your jquery inclusion.

Un-ending image using mouse scroll

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Frog</title>
<script type="text/javascript">
window.onscroll = infinity;
function infinity () {
document.write("<img src='frog.gif'>" + "<br/>");
}
while(window.onscroll){
infinity();
}
</script>
</head>
<body>
<img src='earth.png'>
<br/>
<img src='tiger.jpg'>
<br/>
</body>
</html>
Hi guys, I want to know how would I loop the frog when every time I scroll down the frog image appears again thanks in advance!
If you need to add image when user actually turns mouse wheel (even when no actual scrolling is involved) - you need to capture "mousewheel" event. Universally crossbrowser you can to it like this:
if (document.addEventListener) {
document.addEventListener("mousewheel", MouseWheelHandler, false);
document.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
else {
document.attachEvent("onmousewheel", MouseWheelHandler);
}
If you create a placeholder to hold your future images:
<div id="fdiv">Froggies:</div>
You can add images to it on mousewheeling like this:
function MouseWheelHandler(e) {
var e = window.event || e;
var delta = e.wheelDelta
if (delta < 0)
var img = document.createElement("img");
img.src = "frog.gif";
document.getElementById("fdiv").appendChild(img);
}
What this does is detects whether user scrolls mouse down (delta < 0) and if so - creates a new frog image and adds it to the DIV.
Here's demo: http://jsfiddle.net/Z8AxG/2/ place the mouse over window with words "Froggies:" and turn mouse wheel down.
What you could try is to make a div modify its height when you scroll down (using Javascript). Then apply the image on the background and let it repeat using CSS:
div#infinity {
background-image: url('frog.gif');
background-repeat: repeat-y;
}
With other words, this script will add images when you scroll down:
<!DOCTYPE html>
<html>
<head>
<title>TEST: Infinity Scroll</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var lastScrollTop = 0;
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
$('div#infinity').append(
$('<div>').attr("id", "infinityimage")
);
}
else {
// upscroll code
}
lastScrollTop = st;
});
</script>
<style type="text/css">
html, body {
height: 101%;
}
div#infinityimage {
height: 190px;
background-image: url('https://www.google.nl/images/srpr/logo6w.png');
background-repeat: repeat-y;
}
</style>
</head>
<body>
<div id="infinity">
</div>
</body>
</html>

jquery doesn't seem to load after loading the page in ajax

Hi im having a problem with the page loading another page i have a page a and page b with page a it has an ajax that loads page b ,and page b loads and runs jquery perfectly until i click on page a and then the jquery in page b doesnt seem to can anyone help me with this?
AJAX
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); //Not IE
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP"); //IE
alert("Your browser doesn't support the XmlHttpRequest object. Better upgrade to Firefox.");
}
}
var receiveReq = getXmlHttpRequestObject();
function get() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'b.php', true);
receiveReq.onreadystatechange = handleGet;
receiveReq.send(null);
}
}
function handleGet() {
if (receiveReq.readyState == 4) {
document.getElementById('content').innerHTML = receiveReq.responseText;
}
}
PAGE 1 THAT LOADS THE AJAX AND THE SECOND PAGE
<script src="add.js"></script>
Live Chat
<div id='content' class='content'></div>
PAGE 2 THAT THE PAGE 1 LOADS WITH THE WORKING JQUERY IF LOADED BY IT SELF BUT DOESNT WORK AFTER THE AJAX LOADS THIS PAGE
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Test selctions</title>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#' + $('#selection option:selected').text().toLowerCase()).show();
$('#selection').change(function () {
$('.op').hide();
$('#' + $('#selection option:selected').text().toLowerCase()).show();
});
});
</script>
<style type="text/css">
#plane ,#boat,#car ,#other {
display: none;
}
</style>
</head>
<body>
options:
<select id='selection'>
<option>Pls choose</option>
<option value='1' id='1'>Car</option>
<option value='2' id='2'>Plane</option>
<option value='3' id='3'>Boat</option>
<option value=''>Other</option>
</select><div>
<div id='car' class='op'>you have chosen a car</div>
<div id='plane' class='op'>you have chosen a plane</div>
<div id='boat' class='op'>you have chosen a boat</div>
<div id='other' class='op'>others</div>
</div>
</body>
</html>
Can someone help me with this one and we would really appreciate it! and thanks!
Use live() or $(document).on() function of jquery.
write all jquery function of page2 on page1 and use live() or $(document).on() functions.
it will work...

Categories