Related
I need to adjust my code so that the video is played in the modal that is opened when the user clicks on it.
This code was implemented in a modal that was to display images.
I use JS: https://dimsemenov.com/plugins/magnific-popup/documentation.html
PHP:
<?php
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id=ID';
$xml = simplexml_load_file($url);
$ns = $xml->getDocNamespaces(true);
$xml->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
$elementos = $xml->xpath('//a:entry');
$conteudo = $elementos[0];
$videos_pagina = "12";
$page = isset($_GET['pagina'])?intval($_GET['pagina']-1):0;
$total_paginas = ceil(count($elementos)/$videos_pagina);
if (isset($_GET['pagina']) && is_numeric($_GET['pagina'])) {
$pagina = (int) $_GET['pagina'];
} else {
$pagina = 1;
}
if ($pagina > $total_paginas) {
$pagina = $total_paginas;
}
if ($pagina < 1) {
$pagina = 1;
}
$offset = ($pagina - 1) * $videos_pagina;
$range = 3;
$prevpage = $pagina - 1;
$nextpage = $pagina + 1;
$anterior = $baseurl."/videos/pagina/".$prevpage;
$proxima = $baseurl."/videos/pagina/".$nextpage;
?>
HTML:
<section class="about-section pb30">
<div class="container">
<div class="row">
<?php
foreach (array_slice($elementos, $page*$videos_pagina, $videos_pagina) as $item) {
$media = $item->children('http://search.yahoo.com/mrss/');
$yt = $item->children('http://www.youtube.com/xml/schemas/2015');
$miniatura = $media->group->thumbnail->attributes()->url->__toString();
$titulo = $item->title;
$url_embed = "https://www.youtube.com/embed/".$yt->videoId;
?>
<div class="col-sm-6 col-md-6 col-lg-4">
<div class="gallery_item">
<img class="img-fluid img-circle-rounded w100" src="<?php echo $miniatura; ?>" alt="<?php echo $titulo; ?>">
<div class="gallery_overlay"></span></div>
</div>
</div>
<?php } ?>
<div class="col-sm-12 col-md-12 col-lg-12">
<div class="gallery_item" align="center"><br>
<button type="button" <?php if ($pagina > 1) { }else{ echo "disabled"; } ?> onclick="location.href='<?php echo $anterior; ?>';" class="btn btn-lg btn-thm">Página anterior</button>
<button type="button" <?php if ($pagina != $total_paginas) { }else{ echo "disabled"; } ?> onclick="location.href='<?php echo $proxima; ?>';" class="btn btn-lg btn-thm">Próxima página</button>
</div>
</div>
</div>
</div>
</section>
Currently when the user clicks on the video he opens the modal, however I need the video to be loaded.
How should I do?
You can easily embed or place the YouTube video inside a Bootstrap modal like you do on the normal web pages. Just get the code to embed the video from YouTube site and place it inside the .modal-body element. But there is small problem; the YouTube video doesn't stop automatically when you close the modal window. It will still play in the background.
To solve this problem you can simply toggle the url value of the YouTube's video iframe src attribute dynamically using the jQuery. Let's try out the following example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of Embedding YouTube Video inside Bootstrap Modal</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.bs-example{
margin: 20px;
}
.modal-content iframe{
margin: 0 auto;
display: block;
}
</style>
<script>
$(document).ready(function(){
/* Get iframe src attribute value i.e. YouTube video url
and store it in a variable */
var url = $("#cartoonVideo").attr('src');
/* Assign empty url value to the iframe src attribute when
modal hide, which stop the video playing */
$("#myModal").on('hide.bs.modal', function(){
$("#cartoonVideo").attr('src', '');
});
/* Assign the initially stored url back to the iframe src
attribute when modal is displayed again */
$("#myModal").on('show.bs.modal', function(){
$("#cartoonVideo").attr('src', url);
});
});
</script>
</head>
<body>
<div class="bs-example">
<!-- Button HTML (to Trigger Modal) -->
Launch Demo Modal
<!-- Modal HTML -->
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">YouTube Video</h4>
</div>
<div class="modal-body">
<iframe id="cartoonVideo" width="560" height="315" src="//www.youtube.com/embed/YE7VzlLtp-4" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Please help!
My html body tag appears blank in the browser console while it's not empty. This is happening after I added some javascript tags in the head of my html. It is behaving strange as when I remove all the javascript tags from the head of my html and run my html page in the browser, the javascript code (now removed from the html) appears inside the body tag while it's not even in the entire html. I'm getting frustrated now. Look at my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="res/styles/w3.css">
<link rel="stylesheet" href="res/fonts/icomoon/style.css">
<link rel="stylesheet" href="res/styles/searchform.css">
<link href="res/styles/easy-autocomplete.min.css" rel="stylesheet" type="text/css">
<link href="res/styles/easy-autocomplete.themes.min.css" rel="stylesheet" type="text/css">
<script src="res/js/jquery.easy-autocomplete.min.js" type="text/javascript" ></script>
<link href="res/styles/floats.css" rel="stylesheet" type="text/css">
<link href="res/styles/main.css" rel="stylesheet" type="text/css">
<script src="res/js/getMedia.js" type="text/javascript"></script>
<script src="res/js/jsQR.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
// hide #back-top first
$("#go-to-top").hide();
// fade in #back-top
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('#go-to-top').fadeIn();
} else {
$('#go-to-top').fadeOut();
}
});
// scroll body to 0px on click
$('#go-to-top').click(function () {
$('#content-base').animate({
scrollTop: 0
}, 800);
return false;
});
});
});
</script>
<script type="text/javascript">
var client;
var camStream;
var QRtarget;
function w3_open() {
document.getElementById("nav-menu").style.width = "100%";
document.getElementById("nav-menu").style.opacity = "0.8";
}
function w3_close() {
document.getElementById("nav-menu").style.width = "0";
document.getElementById("nav-menu").style.opacity = "0";
}
function w3_open_cart() {
document.getElementById("nav-cart").style.width = "100%";
document.getElementById("nav-cart").style.opacity = "0.85";
}
function w3_close_cart() {
document.getElementById("nav-cart").style.width = "0";
document.getElementById("nav-cart").style.opacity = "0";
}
</script>
<script type="text/javascript">
function showDialog(wbtn){
switch(wbtn){
case 1:
$('#div-dialog-cover').fadeIn();
$('#div-dialog-back').slideDown();
trackNum();
dialogCmd = 'tracknum';
break;
case 2:
break;
case 3:
break;
case 4:
$('#div-dialog-cover').fadeIn();
$('#div-dialog-back').slideDown();
genQR();
dialogCmd = 'genqr';
break;
case 5:
$('#div-dialog-cover').fadeIn();
$('#div-dialog-back').slideDown();
scanQR();
dialogCmd = 'scanqr';
break;
case 6:
$('#div-dialog-cover').fadeIn();
$('#div-dialog-back').slideDown();
loginForm();
dialogCmd = 'login';
}
}
function QRfound(QRdata){
setTimeout(function() {
closeDialog(QRdata); // You used `el`, not `element`?
}, 1000);
}
function closeDialog(QRdata = ''){
if (dialogCmd == 'genqr'){
} else if (dialogCmd == 'scanqr') {
$('#scanning').hide();
camStream.getTracks().forEach(track => track.stop());
if (QRdata){
alert(QRdata);
}
readingQR = 0;
$('#canvas').hide();
}
$('#dialog-content').html('');
$('#div-dialog-cover').fadeOut();
$('#div-dialog-back').slideUp();
}
</script>
<script type="text/javascript">
var dialogCmd;
function initVars(){
client = "c";
}
function trackNum(){
document.getElementById('dialog-label').innerHTML = 'Enter tracking number';
$('#div-tracker').css('margin-top', '20px');
$('#dialog-label').css('font-size', '0.8em');
$('#div-dialog-body').css('max-height', '300px');
$('#dialog-content').html('<div id="div-tracker"><form id="form-tracker"><label for="tracking-num">Enter tracking Number:</label><input id="tracking-input" type="text" name="tracking-num" /><br><br><button id="submit-track" onclick="submitTrack()">Track now!</button><br><br><div>OR</div><br><button id="btn-QR-track" onclick="trackQR()">Scan a QR to track</button></form></div>');
}
function scanQR(){
document.getElementById('dialog-label').innerHTML = 'Aim at a QR';
$('#div-dialog-body').css('max-height', '350px');
$('#dialog-content').html('<div id="reader"><div id="scanning"></div><canvas id="canvas" style="width:266px" hidden></canvas></div>');
getCamReady();
}
function genQR(){
$('#dialog-label').css('font-size', '0.7em');
$('#dialog-label').css('padding', '0 2px');
document.getElementById('dialog-label').innerHTML = 'Click to regenerate';
$('#div-dialog-body').css('max-height', '350px');
$('#dialog-content').html('<div id="qrview" onclick="regenQR()"></div>');
if (QRtarget == 1){
$('#qrview').css('background', 'url(<?php require('api/getqr.php?t=1') ?>) no-repeat center center');
} else if (QRtarget == 2){
$('#qrview').css('background', 'url(<?php require('api/getqr.php?t=2') ?>) no-repeat center center');
}
$('#qrview').css('background-size', '100%');
}
function regenQR() {
$('#qrview').css('background', '');
if (QRtarget == 1){
$('#qrview').css('background', 'url(<?php require('api/getqr.php?t=1') ?>) no-repeat center center');
} else if (QRtarget == 2){
$('#qrview').css('background', 'url(<?php require('api/getqr.php?t=2') ?>) no-repeat center center');
}
$('#qrview').css('background-size', '100%');
}
</script>
<script type="text/javascript">
function loginForm(){
document.getElementById('dialog-label').innerHTML = 'Login here';
$('#div-dialog-body').css('max-height', '270px');
$('#dialog-content').html('<div id="form-container"><form id="login-form"><label for="username">Username/Email :</label><br><input id="username" style="width: 220px;margin-left:25px"/><br><br><label for="password">Password :</label><br><input id="password" type="password" style="width: 220px;margin-left:25px;"/><br><br>Not registered? Click to sign up.</form></div><br><div id="btn-login" onclick="submitLogin()">Submit</div>');
}
function submitLogin(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username.length == 0) {
alert('Please enter a username');
return false;
}
if (username.length < 8) {
alert('Username should be at least 8 characters long.');
return false;
}
if (password.length == 0) {
alert('Please enter a password');
return false;
}
if (password.length < 6) {
alert('Password should be at least 6 characters long.');
return false;
}
var usernameType;
if (ValidateEmail(username)){
usernameType = 'email';
} else {
if (ValidatePhone(username)){
usernameType = 'phone';
} else {
if (ValidateUsername(username)){
usernameType = 'username';
} else {
alert('Invalid username! Please enter a valid e-mail address, phone number or username.');
return false;
}
}
}
if (ValidatePassword(password)){
return submit(usernameType, username, password);
} else {
alert('Invalid password! Please enter a valid password. Valid password is minimum 6 characters long and contains alphabets, digits and special characters e.g. \"##$%!?\/*-_.|\"');
return false;
}
}
function submit(usernameType, username, password){
}
function ValidateUsername(username){
return true;
}
function ValidatePassword(password){
return false;
}
function ValidatePhone(phone){
return false;
}
function ValidateEmail(mail) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)){
return true;
}
return false;
}
function trackQR(){
closeDialog();
showDialog(5);
}
function connectQR(target){
QRtarget = target;
w3_close();
showDialog(4);
}
</script>
<title>cart</title>
</head>
<body>
<!-- Sidebar -->
<div class="w3-sidebar w3-bar-block" id="nav-menu" style="z-index:1006;">
<button onclick="w3_close()" class="w3-bar-item w3-button" style="background-color:#430032;font-size:0.9em;">Close ×</button>
My Account
My cart
Track my order
Feedback & Dispute
Invite a Friend
About
Contact
</div>
<!-- -->
<!-- cart -->
<div class="w3-sidebar w3-bar-block" id="nav-cart" style="z-index:1006;">
<button onclick="w3_close_cart()" class="w3-bar-item w3-button" style="background-color:#430032;font-size:0.9em;">Close ×</button>
<div style="width: 100%; height: 5%; background-color:red;font-size:0.7em;padding-left:40px;">My cart</div>
My Account
My cart
Link 3
</div>
<!------------>
<!-- dialog new -->
<div id="div-dialog-cover">
</div>
<div id="div-dialog-back">
<div id="div-dialog-close-back">
<div id="dialog-close-btn">
<span class="icon-cancel-circle" onclick="closeDialog()"></span>
</div>
</div>
<div id="div-dialog-body">
<div id="dialog-label"></div>
<div id="dialog-content" style="text-align:center">
</div>
</div>
</div>
<!------------>
<div id="header" class="header">
<div id="h-top-p">
<div id="h-top-menu" class="button" onclick="w3_open()">
<div class="icons">
<i class="icon-menu"></i>
</div>
</div>
<div id="div-wallet">
<div class="assets-main-div">
<span id="wallet" class="icon-coin-dollar" style="font-size: 1.5em"></span>
<div class="assets-vals-out">
<div class="asset-val-div">
1300
<div class="asset-add-div">
+
</div>
</div>
</div>
</div>
</div>
<div id="div-orders-left">
<div class="assets-main-div">
<span id="price-tag" class="icon-price-tags"></span>
<div class="assets-vals-out">
<div class="asset-val-div">
100
<div class="asset-add-div">
+
</div>
</div>
</div>
</div>
</div>
</div>
<div id="h-middle">
<div id="h-middle-logo">
<img id="main-logo" src="res/imgs/title.png">
</div>
</div>
<div id="h-bottom">
<div id="w-button-container">
<div id="w-button-1" class="w-button" onclick="showDialog(1)">
<div class="w-icons">
<span id="w1" class="icon-target2"></span>
</div>
</div>
<div id="w-button-2" class="w-button">
<div class="w-icons">
<span id="w2" class="icon-document-add"></span>
</div>
</div>
<div id="w-button-3" class="w-button">
<div class="w-icons">
<span id="w3" class="icon-star-full"></span>
</div>
</div>
<div id="w-button-4" class="w-button" onclick="showDialog(4)">
<div class="w-icons">
<span id="w4" class="icon-qrcode"></span>
</div>
</div>
<div id="w-button-5" class="w-button" onclick="showDialog(5)">
<div class="w-icons">
<span id="w5" class="icon-camera"></span>
</div>
</div>
</div>
</div>
</div>
<div id="content-base" class="content-base">
</div>
<div id="footer" class="float-footer">
<div class="footer-part">
<span class="icon-bell"></span>
</div>
<div class="footer-part">
<span class="icon-envelope"></span>
</div>
<div class="footer-part">
<span class="icon-gift"></span>
</div>
</div>
<div id="go-to-top" onclick="scroll2top()">
^
</div>
<a href="#" class="float" id="menu-share">
<i class="icon-chat-bubble-dots"></i>
</a>
<ul>
<li><a href="#">
<i class="icon-phone"></i>
</a></li>
<li><a href="#">
<i class="icon-bubbles3"></i>
</a></li>
</ul>
</body>
</html>
The problem is arising because of JavaScript code between line 123-163. Ensure proper parenthesis and syntax.Hope this helps.
As you can see i'm trying to get the data of an html tag which is an <img> tag and getting its src so when i drag and drop an image to my centerbox it goes to a specific page.
The problem is, it only goes to the first link in the first if statement which is "subpages/rice1.htm". Other else if wont work.
function doFirst(){
mypic = document.getElementById('img1');
mypic.addEventListener("dragstart", startDrag, false);
mypictwo = document.getElementById('img2');
mypictwo.addEventListener("dragstart", startDrag2, false);
mypicthree = document.getElementById('img3');
mypicthree.addEventListener("dragstart", startDrag3, false);
mypicfour = document.getElementById('img4');
mypicfour.addEventListener("dragstart", startDrag4, false);
centerbox = document.getElementById("mainbox");
centerbox.addEventListener("dragenter", function(e) {e.preventDefault();}, false);
centerbox.addEventListener("dragover", function(e) {e.preventDefault();}, false);
centerbox.addEventListener("drop", dropped, false);
}
//--------------startDrag FUNCTIONS -----------------------//
function startDrag(e){
var code = '<img id="img1" src="images/rice1.png">';
e.dataTransfer.setData('Text', code);
}
function startDrag2(e){
var code = '<img id="img2" src="images/rice2.png">';
e.dataTransfer.setData('Text', code);
}
function startDrag3(e){
var code = '<img id="img2" src="images/rice3.png">';
e.dataTransfer.setData('Text', code);
}
function startDrag4(e){
var code = '<img id="img2" src="images/rice4.png">';
e.dataTransfer.setData('Text', code);
}
//--------------drop FUNCTIONS -----------------------//
function dropped(e){
e.preventDefault();
centerbox.innerHTML = e.dataTransfer.getData('Text');
centerbox.getElementsByTagName("img")[0].style.width = "500px";
centerbox.getElementsByTagName("img")[0].style.height = "500px";
}
function drop(event){
}
//--------------button functions -----------------------//
function doFunction(){
if (confirm("Are you sure with the sauce?")) {
if(centerbox.src == "images/rice1.png") {
window.location.href = "subpages/rice1.htm";
}
else if (centerbox.src == "images/rice2.png") {
window.location.href = "subpages/rice2.htm";
}
else if (centerbox.src == "images/rice3.png") {
window.location.href = "subpages/rice3.htm";
}
}
}
function reloadPage(){
if (confirm("You sure want to remove sauce?")) {
window.location.reload();
}
}
window.addEventListener ("load", doFirst, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href='https://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
<script src="drag.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3" id="1box">
<h5>SWEET AND SOUR</h5>
<img id="img1" src="images/sauce1.png">
</div>
<div class="col-md-3" id="2box">
<h5>GRAVY</h5>
<img id="img2" src="images/sauce2.png">
</div>
<div class="col-md-3" id="3box">
<h5>SALTED EGG</h5>
<img id="img3" src="images/sauce3.png">
</div>
<div class="col-md-3" id="4box">
<h5>ORIENTAL SAUCE</h5>
<img id="img4" src="images/sauce4.png">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-push-3 col-md-4 mainbox" ondrop="drop(event)" id="mainbox">
<img id="centerimg" src="images/center.png">
</div>
</div>
<div class="row">
<center><h3>Are you sure with the sauce?</h3>
<button id ="sure" onclick="doFunction(); return false;" type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
</button>
<button id ="!sure" onclick="reloadPage(); return false;" type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</center>
</div>
</div>
<!-- hidden images here-->
<img id="s1" class="img5" src="images/rice1.png">
<img id="s2" class="img5" src="images/rice2.png">
<img id="s3" class="img5" src="images/rice3.png">
<img id="s4" class="img5" src="images/rice4.png">
<!--end of hidden images-->
</body>
</html>
Here is the whole updated codes, as stated im trying to make a drag and drag website for food customization.
Use double or triple = operator to compare, like,
if(centerbox.src == "images/rice1.png")
Single = is used to assign value.
function doFunction(){
if (confirm("Are you sure with the sauce?")) {
if(centerbox.src == "images/rice1.png") {
window.location.href = "subpages/rice1.htm";
}
else if (centerbox.src == "images/rice2.png") {
window.location.href = "subpages/rice2.htm";
}
else if (centerbox.src == "images/rice3.png") {
window.location.href = "subpages/rice3.htm";
}
}
}
Update :
You are trying to access the src attribute of a div not an img.
Create a new var of img tag, centerimg = document.getElementById("centerimg"); in doFirst() method.
The .src return the full url of the image source. Compare the image with full path.
Here is the updated snippet
function doFirst(){
mypic = document.getElementById('img1');
mypic.addEventListener("dragstart", startDrag, false);
mypictwo = document.getElementById('img2');
mypictwo.addEventListener("dragstart", startDrag2, false);
mypicthree = document.getElementById('img3');
mypicthree.addEventListener("dragstart", startDrag3, false);
mypicfour = document.getElementById('img4');
mypicfour.addEventListener("dragstart", startDrag4, false);
centerbox = document.getElementById("mainbox");
centerbox.addEventListener("dragenter", function(e) {e.preventDefault();}, false);
centerbox.addEventListener("dragover", function(e) {e.preventDefault();}, false);
centerbox.addEventListener("drop", dropped, false);
centerimg = document.getElementById("centerimg"); //Add this
}
//--------------startDrag FUNCTIONS -----------------------//
function startDrag(e){
var code = '<img id="img1" src="images/rice1.png">';
e.dataTransfer.setData('Text', code);
}
function startDrag2(e){
var code = '<img id="img2" src="images/rice2.png">';
e.dataTransfer.setData('Text', code);
}
function startDrag3(e){
var code = '<img id="img2" src="images/rice3.png">';
e.dataTransfer.setData('Text', code);
}
function startDrag4(e){
var code = '<img id="img2" src="images/rice4.png">';
e.dataTransfer.setData('Text', code);
}
//--------------drop FUNCTIONS -----------------------//
function dropped(e){
e.preventDefault();
centerbox.innerHTML = e.dataTransfer.getData('Text');
centerbox.getElementsByTagName("img")[0].style.width = "500px";
centerbox.getElementsByTagName("img")[0].style.height = "500px";
}
function drop(event){
}
//--------------button functions -----------------------//
function doFunction(){
if (confirm("Are you sure with the sauce?")) {
if(centerimg.src == "http://stacksnippets.net/images/center.png") {
window.location.href = "subpages/rice1.htm";
}
else if (centerimg.src == "http://stacksnippets.net/images/center.png") {
window.location.href = "subpages/rice2.htm";
}
else if (centerimg.src == "http://stacksnippets.net/images/center.png") {
window.location.href = "subpages/rice3.htm";
}
}
}
function reloadPage(){
if (confirm("You sure want to remove sauce?")) {
window.location.reload();
}
}
window.addEventListener ("load", doFirst, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href='https://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
<script src="drag.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3" id="1box">
<h5>SWEET AND SOUR</h5>
<img id="img1" src="images/sauce1.png">
</div>
<div class="col-md-3" id="2box">
<h5>GRAVY</h5>
<img id="img2" src="images/sauce2.png">
</div>
<div class="col-md-3" id="3box">
<h5>SALTED EGG</h5>
<img id="img3" src="images/sauce3.png">
</div>
<div class="col-md-3" id="4box">
<h5>ORIENTAL SAUCE</h5>
<img id="img4" src="images/sauce4.png">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-push-3 col-md-4 mainbox" ondrop="drop(event)" id="mainbox">
<img id="centerimg" src="images/center.png">
</div>
</div>
<div class="row">
<center><h3>Are you sure with the sauce?</h3>
<button id ="sure" onclick="doFunction(); return false;" type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
</button>
<button id ="!sure" onclick="reloadPage(); return false;" type="button" class="btn btn-default" aria-label="Left Align">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</center>
</div>
</div>
<!-- hidden images here-->
<img id="s1" class="img5" src="images/rice1.png">
<img id="s2" class="img5" src="images/rice2.png">
<img id="s3" class="img5" src="images/rice3.png">
<img id="s4" class="img5" src="images/rice4.png">
<!--end of hidden images-->
</body>
</html>
your comparison is not correct.use double or triple equal mark.you are assigning values to src .
if(centerbox.src=="images/rice1.png"){ // same for other is/else blocks
read more about equal mark here
in your code you assign "images/rice1.png" to centerbox.src.and then you check if(centerbox.src). in javascript if("something") is evaluated to true so it never goes to else if blocks .
I have TWO main questions that I really would have help with.
I have googled and searched for some day now without any help, but if you know any links that I maybe haven't watched or any site with help, then give me.
I would appreciated it, OR if you already have the code/sample code, would help :-)
I work with PhoneGap & JQuery Mobile right now, and the thing is this.
I have a 'textarea' there you write something, then a save button, what I want it to do is that when I press the save-button, the textvalue I wrote in the textarea would get saved in a listview in another page of the app. I have looked at "localstorage" but nothing works correctly.
(Also, if you write something in textarea and you press the cancel button, the text in the textarea should be deleted next time you go in to that page.)
The second question is:
When I press the save button, it should begin to count, in seconds, minutes, hours, days.
Think of it like this. I write "toothbrush" in the textarea and press save, now when I go to the listview-page, I can see it says toothbrush in the listview, beside the text it says 1m, 5m, 1h, it just update when it was last time I bought or changed the toothbrush, so next time I open the app, I can see "TOOTHBRUSH: 4Days, 16HRS, 52MINS AGO". In that way I can check when I bought something, or changed something.
This is my codes, both html & .js, what should I do so this mission will work.
Any suggestions, sites, or code you guys have that would help?
Thank you so much.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Last Time I Did It!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="lib/jquery-1.6.4.js"></script>
<script src="lib/jquery.mobile-1.1.0.js"></script>
<link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet">
<link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet">
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h1>Last time I did it</h1>
</div>
<div data-role="content"></div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#page2" data-transition="slide" id="add" data-rel="page">ADD</a>
</li>
<li>
<a data-role="button" href="#page2" data-transition="slide" id="show" data-rel="page">SHOW</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="header">
<h1>Add event</h1>
</div>
<div data-role="content">
<textarea></textarea>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#page3" data-transition="slide" id="save">SAVE</a>
</li>
<li>
<a data-role="button" href="#page1" id="cancel" data-transition="slide" data-direction="reverse" data-rel="page">CANCEL</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page3">
<div data-role="header">
Back
<h1>Events</h1>
</div>
<div data-role="content">
<ol data-role="listview" id="orderedList" data-inset="true"></ol>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" id="edit">EDIT</a>
</li>
<li>
<a data-role="button" id="delete">DELETE</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
and my almost empty -js code.
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('click', '#add', function(){
$.mobile.navigate( "#page2", { transition : "slide", info: "info about the #bar hash" });
});
});
function save ()
{
var fieldValue = document.getElementById('textarea').value;
localStorage.setItem('content', orderedList);
}
EDIT:
Here is my new html & js file, after looked at your awesome code-example, but when I run it on my phone with phonegap, still, the save, cancel, the time and even the saved text will not show up.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Last Time I Did It!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="lib/jquery-1.6.4.js"></script>
<script src="lib/jquery.mobile-1.1.0.js"></script>
<link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet">
<link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet">
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h1>Last time I did it</h1>
</div>
<div data-role="content"></div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#page2" data-transition="slide" id="add" data-rel="page">ADD</a>
</li>
<li>
<a data-role="button" href="#page3" data-transition="slide" id="show" data-rel="page">SHOW</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="header">
<h1>Add event</h1>
</div>
<div data-role="content">
<textarea id="newItemText"></textarea>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" href="#" data-transition="slide" id="btnSave">SAVE</a>
</li>
<li>
<a data-role="button" href="#page1" id="btnCancel" data-transition="slide" data-direction="reverse" data-rel="page">CANCEL</a>
</li>
</ul>
</div>
</div>
</div>
<div data-role="page" id="page3">
<div data-role="header">
Back
<h1>Events</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="orderedList" data-inset="true">
</ul>
</div>
<div data-role="footer">
<div data-role="navbar">
<ul>
<li>
<a data-role="button" id="edit">EDIT</a>
</li>
<li>
<a data-role="button" id="delete">DELETE</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
And the JS file.
$(document).on('pagebeforeshow', '#page3', function(){
//setup the current list
if(localStorage.getItem('TaskList')){
var TheList = [];
TheList = JSON.parse(localStorage.getItem('TaskList'));
var items = '';
for (var i = 0; i < TheList.length; i++) {
items += '<li><h3>' + TheList[i].text + '</h3><p>' + timeAgo( (new Date(TheList[i].time).getTime())/1000) + ' ago<p></li>';
}
$('#orderedList').empty().append($(items)).listview('refresh');
}
});
$(document).on('pageinit', '#page2', function(){
$('#btnCancel').on("click", function(){
$('#newItemText').val(''); //CLEAR TEXT AREA
});
$('#btnSave').on("click", function(){
var TheList = [];
if(localStorage.getItem('TaskList')){
TheList = JSON.parse(localStorage.getItem('TaskList'));
}
var newitem = $('#newItemText').val();
var task = {text: newitem, time: new Date() };
TheList.push(task);
localStorage.setItem('TaskList', JSON.stringify(TheList));
$('#newItemText').val(''); //CLEAR TEXT AREA
$.mobile.navigate( "#page3", { transition : "slide" });
});
});
function timeAgo(time){
var units = [
{ name: "second", limit: 60, in_seconds: 1 },
{ name: "minute", limit: 3600, in_seconds: 60 },
{ name: "hour", limit: 86400, in_seconds: 3600 },
{ name: "day", limit: 604800, in_seconds: 86400 },
{ name: "week", limit: 2629743, in_seconds: 604800 },
{ name: "month", limit: 31556926, in_seconds: 2629743 },
{ name: "year", limit: null, in_seconds: 31556926 }
];
var diff = (new Date() - new Date(time*1000)) / 1000;
if (diff < 5) return "now";
var i = 0;
while (unit = units[i++]) {
if (diff < unit.limit || !unit.limit){
var diff = Math.floor(diff / unit.in_seconds);
return diff + " " + unit.name + (diff>1 ? "s" : "");
}
};
}
SOLUTION:
The JSFiddler code-example, the demo is perfect and are based on jQuery 1.9.1 & jQuery Mobile 1.3.0b1, I used 1.6.4 & 1.1.0.
After updating this two .js files, everything worked on PhoneGap!
Here is a DEMO
There are many questions within your problem, so I will probably not manage to answer all of them. To use localStorage with an array of 'tasks' you use JSON.stringify when saving and JSON.parse when retrieving.
So, each time page3 is displayed, you retrieve the current list of items from localStorage, create list items, empty the list and then append the created items :
$(document).on('pagebeforeshow', '#page3', function(){
//setup the current list
if(localStorage.getItem('TaskList')){
var TheList = [];
TheList = JSON.parse(localStorage.getItem('TaskList'));
var items = '';
for (var i = 0; i < TheList.length; i++) {
items += '<li><h3>' + TheList[i].text + '</h3><p>' + TheList[i].time + '<p></li>';
}
$('#orderedList').empty().append($(items)).listview('refresh');
}
});
When entering a new item, you want to store the text and the current time, so use an object. First get the current list from localStorage, then create the new item and add it to the list, finally save back to localStorage clear the textarea and navigate to page3. The cancel button just clears the textarea:
$(document).on('pageinit', '#page2', function(){
$('#btnCancel').on("click", function(){
$('#newItemText').val(''); //CLEAR TEXT AREA
});
$('#btnSave').on("click", function(){
var TheList = [];
if(localStorage.getItem('TaskList')){
TheList = JSON.parse(localStorage.getItem('TaskList'));
}
var newitem = $('#newItemText').val();
var task = {text: newitem, time: new Date() };
TheList.push(task);
localStorage.setItem('TaskList', JSON.stringify(TheList));
$('#newItemText').val(''); //CLEAR TEXT AREA
$.mobile.navigate( "#page3", { transition : "slide" });
});
});
At first sorry if i have some typing errors english is not my main language but i try to do my best to explain it at my best.
I am working on a test app with a note database.
It works fine with adding and deleting but there is a small problem...
At the moment that i add a note (on edit.html) and want to go back to the index.html page it is not going back.
i am working with multiple data-page-role pages so each page has his own id.
The code that i use for the note database:
index.html Header:
$("#homePage").live('pageinit', function() {
init();
});
index.html data-page-role
<div data-role="page" id="homePage" data-add-back-btn="true" class="noteclass">
<!-- HEader -->
<div data-role="header" >
<h1>Notitie Database</h1>
</div>
<!-- Main content div -->
<div data-role="content" id="mainContent">
<ul data-role="listview" id="noteTitleList"></ul><br />
</div>
<div data-role="content">
Voeg notitie toe
</div>
<!-- Footer -->
<div data-role="footer" id="footer"> <img src="a12.png" />
<p>© 2012 - Swen Kooij / Paksha Thullner / Johnny Jansen</p>
</div>
</div>
Edit.html (here u can add/change/remove the notes)
<!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" />
</head>
<body>
<div data-role="page" id="editPage">
<!-- HEader -->
<div data-role="header">
<h1>Write Note</h1>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#Delete').click(function() {
DeleteNote($('#noteId').val());
});
$('#addNote').click(function() {
var data = {title:$("#noteTitle").val(),
body:$("#noteBody").val(),
id:$("#noteId").val()
};
saveNote(data);
});
});
</script>
<div data-role="content">
<form id="editNoteForm" method="post">
<input type="hidden" name="noteId" id="noteId" value="">
<div data-role="fieldcontain">
<label for="noteTitle">Title</label>
<input type="text" name="noteTitle" id="noteTitle">
</div>
<div data-role="fieldcontain">
<label for="noteBody">Note</label>
<textarea name="noteBody" id="noteBody"></textarea>
</div>
<div data-role="fieldcontain">
<button id="addNote">Opslaan</button>
</div>
</form>
<button id="Delete">Verwijder</button>
</div>
Ga terug
<!-- Footer -->
<div data-role="footer" id="footer"> <img src="a12.png" />
<p>© 2012 - Swen Kooij / Paksha Thullner / Johnny Jansen</p>
</div>
</div>
</body>
</html>
And here is the backend code that i use for the note database
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
phoneready();
}
function setupTable(tx){
tx.executeSql("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY,title,body,updated)");
}
function getEntries() {
dbShell.transaction(function(tx)
{
tx.executeSql("select id,title,body, updated from notes order by id asc", dbErrorHandler, renderEntries)
}, function(){ alert ("Error getentries");
});
}
function renderEntries(tx,results){
if (results.rows.length == 0) {
$("#mainContent").html("<p>Je hebt nog geen notities.</p>");
} else {
var s = "";
for(var i=0; i<results.rows.length; i++) {
s += "<li><a href='edit.html?id="+results.rows.item(i).id + "'>" + results.rows.item(i).title + "</a></li>";
}
$("#noteTitleList").html(s);
$("#noteTitleList").listview("refresh");
}
}
function saveNote(note) {
//Sometimes you may want to jot down something quickly....
if(note.title == "") note.title = "[Geen Titel]";
dbShell.transaction(function(tx) {
if(note.id == "")
{
tx.executeSql("insert into notes(title,body,updated) values(?,?,?)",[note.title,note.body, new Date()]);
}
else
{
tx.executeSql("update notes set title=?, body=?, updated=? where id=?",[note.title,note.body, new Date(), note.id]);
}
}, function(){ alert ("Error savenote");},
function()
{
window.navigator.location("index.html#homePage");
});
}
function DeleteNote(id){
dbShell.transaction(
function(tx)
{
tx.executeSql('Delete FROM notes where id=' + id);
},
function(){ alert ("Error deletenote");},
function(err)
{
window.navigator.location("index.html#homePage");
});
}
function phoneready(){
dbShell = window.openDatabase("SimpleNotes", 2, "SimpleNotes", 1000000);
setupTable();
}
function init(){
getEntries();
//edit page logic needs to know to get old record (possible)
$("#editPage").live("pagebeforeshow", function() {
//get the location - it is a hash - got to be a better way
var loc = window.location.hash;
if(loc.indexOf("?") >= 0) {
var qs = loc.substr(loc.indexOf("?")+1,loc.length);
var noteId = qs.split("=")[1];
//load the values
dbShell.transaction(
function(tx) {
tx.executeSql("select id,title,body from notes where id=?",[noteId],function(tx,results) {
$("#noteId").val(results.rows.item(0).id);
$("#noteTitle").val(results.rows.item(0).title);
$("#noteBody").val(results.rows.item(0).body);
});
}, dbErrorHandler);
}
});
}
As u can see at saveNote and on deleteNote i call the function window.navigator.location("index.html#homePage");
I did this as far as i tried with $.mobile.changePage("index.html#homePage"); it will go back but then it won't run the init(); function at the header script.
I hope i explained it all correct and if there are any questions please let me know.
I will try then to do my best at explaining it.
edit:
More information:
At first thank you for your answer, i got multiple data-role-pages.
A extra example:
<div data-role="page" id="page5" data-add-back-btn="true">
<!-- Header -->
<div data-role="header" >
<h1>Locatie</h1>
</div>
<!-- Main content div -->
<div data-role="content">
<p id="geolocation" onClick="onDeviceReady()">Op zoek naar uw locatie ...</p>
<img src="" id="map" width="100%" height="" />
<h4>Omgeving</h4>
<img src="" id="map2" width="100%" height="" />
</div>
<div data-role="footer" id="footer"> <img src="a12.png" />
<p>© 2012 - Swen Kooij / Paksha Thullner / Johnny Jansen</p>
</div>
</div>
You are trying to change page with deep link "index.html#homePage" .
JqueryMobile does not support that. When you pass a file, he will load ONLY the first page of that file.
This means that when you pass "index.html#homePage", he'll only consider the "index.html" and load the first page on that file.
I don't know it for sure, but if in your index.html file only have the "homePage", change function window.navigator.location to:
$.mobile.changePage("index.html")
And of course do the same for the anchor tag .
I use:
window.location = "#home";