Glassbox.js javascript plugin doesn't work in JQuery - javascript

So I have the following code, and glassLoad() does NOT work when called from a JQuery context. I have isolated the problem to one specific line, myBox.apos('170px', '150px'); which seems to stop the entire function from running, but ONLY when called from JQuery. If I use a standard onclick="glassLoad();" it runs the function perfectly, but if i include the function in JQuery it stops the WHOLE JQuery function from running:
#model IEnumerable<OneEightyWebApp.Models.PropertyDB>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" media="screen" />
<script src="../../Content/javascripts/glassbox/glassbox.js" type="text/javascript"></script>
<head>
<title></title>
<script type="text/javascript">
function populate() {
var select = document.getElementById("centres");
for (var i = 1; i <= 10; i++) {
var option = document.createElement("option");
option.value = i;
option.text = i;
select.appendChild(option);
}
}
function divGenerator() {
var div;
for (var i = 1; i <= document.getElementById("revisions").value; i++) {
div = document.createElement("div");
div.className = "class1";
div.innerHTML = "Space " + i;
div.style.width = "100px";
div.style.height = "100px";
div.style.float = "left";
document.getElementById("container2").appendChild(div);
}
}
function glassLoad() {
path_to_root_dir = "../../Content/";
var myBox = new GlassBox();
myBox.init('myBox', '128px', '62px', 'hidden');
myBox.apos('170px', '150px');
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", ".class1", function () {
glassLoad();
alert("div clicked");
});
});
</script>
</head>
<body>
<!--
popup
-->
<div id="container1" style="width: auto; height: 50px;">
<button style="margin: auto; vertical-align: top; float: left; font-size: 16px;" type="button" onclick="divGenerator();">Generate</button>
#Html.DropDownList("revisions", (List<SelectListItem>)ViewData["revisions"])
</div>
<div id="container2" style="margin: 10px; float: left;"></div>
<div id="myBox">Hello!</div>
</body>

To make this run with PrototypeJS
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"> </script>
<script type="text/javascript">
document.observe('dom:loaded',function(){
$$("body")[0].on('click', ".class1", function () {
glassLoad();
alert("div clicked");
});
});
</script>
This will trigger when the DOM is loaded and uses the CSS selector method $$() and selects the first element in the list that is returned and then attaches to the click event of that element.
The rest of your javascript doesn't look like it depends on jQuery or Prototype so you should be able to swap this code snippet into your code.

It appears Glassbox.js does not support jQuery. It is built to work with Prototype, which is an alternative framework. So you'll have to either use Prototype instead or find an alternative plugin.

Related

Toggle button : Javascript toggle doesn't works locally

I try to create a toggle button in order to show/hide some content. For the moment, I use that :
// test.js
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
#content {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<button id="toggle">Click Me</button>
<div id="content">Hello World</div>
</body>
</html>
If I use these code with codepen or JSFiddle, all works fine, but when I try it locally, ( when I click on my index.html file, open it with firefox or an other browser ) my button "Click Me" doesn't works.
When I click on it, nothing happens...
Someone to show me why ?
You could make your function to be fired on load event.
Possible example
(function() {
var loadedContent = {
init: function() {
window.addEventListener("load", function(event) {
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.style.display = (content.dataset.toggled ^= 1) ?
"block" :
"none";
});
});
}
};
loadedContent.init();
})();
#content {
display: none;
}
<button id="toggle">Click Me</button>
<div id="content">Hello World</div>

Javascript Running on JSFiddle but not on a webpage

Ok so I have a code that would show different forms based on dropdown selection
Here's the fiddle to that..
Well its always giving me Test1 which means its not changing the div display, it's working on JSFiddle but not on the webpage..
and here's my webpage markup
<html>
<body>
<style>
.hidden {
display: none;
}
</style>
<script type='text/javascript'>
document.getElementById('options').onchange = function() {
var i = 1;
var myDiv = document.getElementById(i);
while(myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
</script>
<select name="options" id="options">
<option value="1"> Display </option>
<option value="2">Wka</option>
</select>
<div id="1" class="hidden" style="display: block">Test 1</div>
<div id="2" class="hidden">Test 2</div>
</body>
</html>
That is because in the fiddle your code is set to run at onLoad, but in your code its running before the DOM is created.
Wrap your code into a window.onload event like this:
window.onload = function()
{
document.getElementById('options').onchange = function() {
var i = 1;
var myDiv = document.getElementById(i);
while(myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
};
Anyway, like #positivew remembered, your code misses the <head> tag. Is semantically correct to put your JS scripts inside it.
The best thing to do when such problem comes works in jsfiddle and not on webpage is to see the source of the fiddle page.
Your source of the fiddle appears as:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
.hidden
{
display: none;
}
</style>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
document.getElementById('options').onchange = function()
{
var i = 1;
var myDiv = document.getElementById(i);
while(myDiv)
{
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
}//]]>
</script>
</head>
<body>
<select name="options" id="options">
<option value="1"> Test1 </option>
<option value="2">Test2</option>
</select>
<div id="1" class="hidden" style="display: block">Test 1</div>
<div id="2" class="hidden">Test 2</div>
</body>
</html>
Paste the above code directly and it will work.
After pasting the code directly then you can remove unncecessary lines like below from the fiddle:
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
You need a onload function so your code is run after your HTML is loaded. Try this:
window.onload = function () {
document.getElementById('options').onchange = function () {
var i = 1;
var myDiv = document.getElementById(i);
while (myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
}
You can also add the code after all your HTML, before the end of the body tag.
And note that in your post you are missing <head> tags.
You seem to be missing <head> tags.
Jsfiddle is running your script .onload of the window object, without you realizing it. This allows your script to pause on execution until the DOM is ready to be manipulated.
To have it work in your own environment, you can:
Place the entire script after the HTML you're trying to manipulate (e.g. end of the <body>)
Leave your code above the <body> and run it onload of the window object, e.g.
window.onload = function () {
document.getElementById('options').onchange = function () {
var i = 1;
var myDiv = document.getElementById(i);
while (myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
}
The page is loaded into the DOM from the top down.
Your document.getElementById('options').onchange is being called before the element with id options exists in the DOM.
If you put your script below the divs, it'll work because the divs are now there before the script is called.

Identifying and fixing javascript/prototype/jquery conflicts?

I am experiencing an issue with my scripts to which I cannot find a proper fix. I have this code, which uses glassbox.js and all its extras, which uses to work (it displayed the glassbox appropriately) but since I added JQuery to the file it has stopped working. I am not sure how to rearrange or call the scripts so that it functions again. The commented out lines myBox.whatever are the lines causing the issue specifically:
#model OneEightyWebApp.Models.Centres
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" media="screen" />
<head>
<title></title>
<script src="../../Content/javascripts/prototype.js" type="text/javascript"> </script>
<script src="../../Content/javascripts/scriptaculous/effects.js" type="text/javascript"></script>
<script src="../../Content/javascripts/glassbox/glassbox.js" type="text/javascript"></script>
<script type="text/javascript">
var spaces = #Html.Raw(Json.Encode(ViewData["spaces"]))
function glassLoad() {
path_to_root_dir = "../../Content/";
var myBox = new GlassBox();
myBox.init('myBox', '600px', '400px', 'hidden', '', true, true);
// myBox.apos('300', '300px');
// myBox.appear();
alert("clicked");
}
</script>
<script src="../../Content/javascripts/prototype.js"> </script>
<script type="text/javascript">
document.observe('dom:loaded', function () {
$$("body")[0].on('click', ".class1", function () {
var myBox = document.getElementById("myBox");
myBox.style.display = "block";
glassLoad();
});
});
</script>
<script src="../../Content/jquery.js"></script>
<script type="text/javascript">
jQuery(function () {
var array = [];
jQuery("#centres").change(function () {
var selectedCentre = $("#centres option:selected").text();
$.getJSON("/Centres/output?centreName=" + selectedCentre, function (results) {
var data = results;
document.getElementById("container2").innerHTML = "";
var div;
for (var i = 0; i < document.getElementById("centres").value; i++) {
div = document.createElement("div");
div.className = "class1";
div.innerHTML = "Shop " + data[i];
div.innerHTML += "<br>";
div.innerHTML += "Floor Space: <b>" + spaces[i] + " m2 </b>";
div.style.width = "100px";
div.style.height = "100px";
div.style.padding = "0px";
div.style.float = "left";
document.getElementById("container2").appendChild(div);
}
});
});
});
</script>
</head>
<body>
<div id="container1" style="width: auto; height: 50px;">
<button style="margin: auto; vertical-align: top; float: left; font-size: 16px;" type="button" onclick="glassLoad();">Generate</button>
#Html.DropDownList("centres", (List<SelectListItem>)ViewData["centres"])
<select id="mySelect"></select>
</div>
<div id="container2" style="margin: 10px; float: left;"></div>
<div id="myBox" style="display: none; width: 600px; height: 400px;">
<div id="exitButton" style="position: absolute; left: 564px; bottom: 173px; z-index: 1001;" title="close">
<a href="javascript:THIS.fade();">
<img id="exitImage" style="border: none;" src="../../Content/javascripts/glassbox/skins/exitButton.png"></a>
</div>
</div>
</body>
You have to put jQuery in noConflict and pass $ into the ready event here:
$.noConflict();
jQuery(function ($) {
var array = [];
... // use $ from now on instead of jQuery
That's one way of doing it, check the docs there are other patterns.

Get name of dynamically created div in javascript?

I cannot seem to make my javascript .click() method work with my dynamically created divs. In this code I have divs created each under the class name "class1" but my click method does not seem to detect their existence. Here is my code:
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" media="screen" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function populate() {
var select = document.getElementById("centres");
for (var i = 1; i <= 10; i++) {
var option = document.createElement("option");
option.value = i;
option.text = i;
select.appendChild(option);
}
}
function divGenerator() {
var div;
for (var i = 1; i <= document.getElementById("centres").selectedIndex + 1; i++) {
div = document.createElement("div");
div.className = "class1";
div.innerHTML = "Space " + i;
div.style.width = "100px";
div.style.height = "100px";
div.style.float = "left";
document.getElementById("container2").appendChild(div);
}
}
function glassLoad() {
path_to_root_dir = "../../Content/";
var myBox = new GlassBox();
myBox.init('myBox', '128px', '62px', 'hidden');
myBox.apos('170px', '150px');
}
// window.onload = populate;
$(function () {
$("container2").on("click", ".class1", function () {
alert("The div was clicked.");
});
});
</script>
<div id="container1" style="width: auto; height: 50px;">
<div id="myBox">Hello World!</div>
<button style="margin: auto; vertical-align: top; float: left; font-size: 16px;" type="button" onclick="divGenerator();">Generate</button>
#Html.DropDownList("centres")
</div>
<div id="container2" style="margin: 10px; float: left;" />
<head>
<script type="text/javascript" src="../../Content/javascripts/glassbox/glassbox.js"></script>
<style type="text/css">
#myBox #myBox_content {
padding: 2px;
font-family: verdana, arial, helvetica;
font-size: 12px;
}
</style>
<title></title>
</head>
<body>
<!--
popup
-->
</body>
And here is what it returns (taken from google chrome):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="description" content="Description of your web page goes here." />
<meta name="keywords" content="Keywords for you web page go here. Each keyword or group of keyword phrases are separated by a comma. Keep this list short and relevant to the content and title of this specific page." />
<title>OneEighty Asset Manager
</title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="header">
<div id="logo">
<p></p>
</div>
</div>
<!-- end #header -->
<div id="menu">
<ul>
<li>Home</li>
<li>About</li>
</ul>
</div>
<!-- end #menu -->
<div id="wrapper">
<div class="btm">
<div id="page">
<h1>
<img src="../../Content/Images/1Eighty.png" alt="" style="height: 100px; width: 750px;" /></h1>
<div id="content">
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript">
function populate() {
var select = document.getElementById("centres");
for (var i = 1; i <= 10; i++) {
var option = document.createElement("option");
option.value = i;
option.text = i;
select.appendChild(option);
}
}
function divGenerator() {
var div;
for (var i = 1; i <= document.getElementById("centres").selectedIndex + 1; i++) {
div = document.createElement("div");
div.className = "class1";
div.innerHTML = "Space " + i;
div.style.width = "100px";
div.style.height = "100px";
div.style.float = "left";
document.getElementById("container2").appendChild(div);
}
}
function glassLoad() {
path_to_root_dir = "../../Content/";
var myBox = new GlassBox();
myBox.init('#myBox', '128px', '62px', 'hidden');
myBox.apos('170px', '150px');
alert("div clicked");
}
// window.onload = populate;
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#container2").on("click", ".class1", function () {
path_to_root_dir = "../../Content/";
var myBox = new GlassBox();
myBox.init('#myBox', '128px', '62px', 'hidden');
myBox.apos('170px', '150px');
alert("div clicked");
});
});
</script>
<div id="container1" style="width: auto; height: 50px;">
<button style="margin: auto; vertical-align: top; float: left; font-size: 16px;" type="button" onclick="divGenerator();">Generate</button>
<select id="centres" name="centres"><option>Southdale</option>
<option>Sasolburg</option>
<option>Sandton City</option>
<option>Greenstone</option>
<option>Morningside</option>
<option>Easgate</option>
<option>Bedfordview</option>
<option>Fourways</option>
<option>Linksfield Terrace</option>
<option>Carlton Centre</option>
<option>testcentre1</option>
<option>testcentre2</option>
<option>testcentre3</option>
</select>
</div>
<div id="container2" style="margin: 10px; float: left;" />
<head>
<script type="text/javascript" src="../../Content/javascripts/glassbox/glassbox.js"></script>
<style type="text/css">
#myBox #myBox_content {
padding: 2px;
font-family: verdana, arial, helvetica;
font-size: 12px;
}
</style>
<title></title>
</head>
<body>
<!--
popup
-->
</body>
</div>
<!-- end #content -->
<div style="clear: both;">
</div>
</div>
<!-- end #page -->
</div>
</div>
<div id="footer">
<p>
Copyright (c) 2009 1eightyintra.com. All rights reserved.
</p>
</div>
<!-- end #footer -->
</body>
</html>
Because the element doesn't exist in the DOM on page load, you need to use an event delegate, such as on:
$(function () {
$("body").on("click", ".class1", function () {
alert("The div was clicked.");
});
});
Or for pre-1.7 jQuery, use delegate:
$(function () {
$("body").delegate(".class1", "click", function () {
alert("The div was clicked.");
});
});
click only binds handlers to elements that were present in the DOM when you called it.
Instead, use the jQuery on method:
$(document).ready(function () {
$("body").on("click", ".class1", function () {
alert("The div was clicked.");
});
});
You will need to re-apply the click handler to the newly created divs.

Can't dynamically add anchor tag after enclosing div inside a div with data-role="page"

I want to dynamically add anchor tag to the div="myDiv".
It works fairly as long as I didn't enclose it inside another dive with data-role="page".
I want to enclose it in a page so that it can be called as page on a button link.What could be the problem.
Below is the code.
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<!--<script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script> -->
<style>
figure{
float:left
}
figcaption{
font-size: small;
}
img {
float:left;
}
a {
color: black;
text-decoration: none;
}
a:hover {
color:black;
text-decoration:none;
cursor:pointer;
}
</style>
</head>
<body>
<div data-role="page"> //remove this and it will start working.
<div data-role="div" id="myDiv" ></div>
<div data-role="popup" id="popupMap1" class="ui-content" data-overlay-theme="a" data-theme="a" data-corners="false" data-tolerance="15,15"></div>
</div>
<script>
function play(id){
document.getElementById("popupMap1").innerHTML="<a href='#' data-rel='back' data-role='button' data-theme='a' data-icon='delete' data-iconpos='notext' class='ui-btn-right'>Close</a><iframe src='http://www.youtube.com/embed/"+id+"' width='480' height='320' seamless='' id='plyerIframe1'></iframe>";
}
</script>
<script type="text/javascript"
src="http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?time=today&alt=json-in-script&callback=showMyVideos2&max-results=15&format=5">
</script>
<script type="text/javascript">
var title=new Array();
var thumbnailUrl=new Array();
var playerUrl=new Array();
var mydiv = document.getElementById("myDiv");
var duration=new Array();
var views=new Array();
var idi=new Array();
function showMyVideos2(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = ['<ul class="videos">'];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
title[i] = entry.title.$t.substr(0,20);
thumbnailUrl[i] = entry.media$group.media$thumbnail[0].url;
playerUrl[i] = entry.media$group.media$content[0].url;
duration[i]= entry.media$group.media$content[0].duration;
views[i]= entry.yt$statistics.viewCount;
var aTag = document.createElement('a');
aTag.setAttribute('href','#popupMap1');
aTag.setAttribute('data-rel','popup');
aTag.setAttribute('data-position-to','window');
aTag.setAttribute('data-theme','b');
aTag.setAttribute('data-inline','true');
//idi[i]=playerUrl[i].substring(25,36);
idi[i]=entry.media$group.yt$videoid.$t;
aTag.innerHTML ="<figure onclick='play(idi["+i+"])'><figcaption>"+title[i]+"...</figcaption><img src="+thumbnailUrl[i]+" width='200px' height='150px' ><footer>Duration: "+duration[i]+" seconds<br><span>Total Views: "+views[i]+"</span></footer></figure>" ;
mydiv.appendChild(aTag);
}
}
</script>
</body>
</html>
I've made a jsFiddle with the solution for your problem.
Explanation:
When you use the data-role="page" div, you're engaging jQuery-Mobile framework, which will perform some operations on the DOM, re-arranging some elements. I won't go any deeper into this as I'm really not sure what exactly goes on behind the scenes, but what seemed to be happening was that jQuery-Mobile had not yet finished rendering the page at the time the youtube script was trying to call showMyVideos2.
So I removed the <script> tag where you included that script, and instead added the following javascript code:
$(document).on('pageshow', function() {
$.getScript("http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?time=today&alt=json-in-script&callback=showMyVideos2&max-results=15&format=5");
});
Two things you should know about this:
I've put this code in a callback for the pageshow event, to ensure that jQuery-Mobile has finished all the work it needs to do on the page before you start any DOM manipulation. Other jQuery-Mobile events such as pagechange and pagecreate would also have worked.
I loaded the youtube script using jQuery's getScript() method, which allows you to dynamically retrieve an external script and execute it. It is actually just a shorthand notation for the following case of the $.ajax() method:
$.ajax({
url: "http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?time=today&alt=json-in-script&callback=showMyVideos2&max-results=15&format=5",
dataType: "script"
});

Categories