trying to make light box, getting Jquery Syntax error - javascript

I am trying to get a light box to display when you click a tag on the page. Basically it the js is trying to take the href and use it to get the width. (not the best at js and jquery) so any help is gonna be very much appreciated.
error im getting:
Error: Syntax error, unrecognized expression: #?w=500, a[name=?w=500] # http://code.jquery.com/jquery-latest.js:4680
html
<a href="#?w=500" rel="diff" class="poplight">
<h1 class="blue">diff</h1>
</a>
<div id="diff" class="popup_block">
<p>text in light box</p>
</div>
Jquery:
<script type="text/javascript">
$(document).ready(function() {
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
window.alert('2 test in the popup function ');
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('Close');
//Define margin for center alignment (vertical horizontal) - we add 80px to the height/width to accomodate for the padding and border width defined in the css
var popMargTop = ($('#' + popID).height() - 80) / 2;
var popMargLeft = ($('#' + popID).width()) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=90)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=90)'}) is used to fix the IE Bug on fading transparencies
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove(); //fade them both out
});
return false;
});
});
</script>

This isn't a direct answer, but did you do know that you can create your own attributes?
<a popupwidth="500" rel="diff" class="poplight">
<h1 class="blue">diff</h1>
</a>
would work fine:
$('a.poplight[popupwidth]').click(function() {
//...
var popWidth = $(this).attr('popupwidth');
//...
}
Your HTML editor might complain, but this is perfectly legal HTML and will function fine. In case you want to be XML-compliant, you can create your own XML Schema and reference it via a namespace.
Schema
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XhtmlAddons"
targetNamespace="http://somekindofid/XhtmlAddons.xsd"
elementFormDefault="qualified"
xmlns="http://somekindofid/XhtmlAddons.xsd"
xmlns:mstns="http://somekindofid/XhtmlAddons.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:attribute name="popupwidth" type="xs:int" />
</xs:schema>
HTML
<!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"
xmlns:addon="http://somekindofid/XhtmlAddons.xsd">
<!-- ... -->
<a addon:popupwidth="500" rel="diff" class="poplight">
<h1 class="blue">diff</h1>
</a>
<!-- ... -->
</html>
jQuery*
$('a.poplight[addon\\:popupwidth]').click(function() {
//...
var popWidth = $(this).attr('addon\\:popupwidth');
//...
}
Please note, however, that jQuery does not natively support XML namespaces so you may run into trouble if you do anything advanced. The first example above (without the namespaces) is preferred unless your really, really need XML compatibility for other reasons.
UPDATE
If you are validating against HTML 5, you should NOT use the schema. Just prepend your custom attribute with "data-":
HTML
<a data-popupwidth="500" rel="diff" class="poplight">
<h1 class="blue">diff</h1>
</a>
jQuery
$('a.poplight[data-popupwidth]').click(function() {
//...
var popWidth = $(this).attr('data-popupwidth');
//...
}
See HTML 5 data- Attributes by Jon Resig

Related

How could I adjust this js generated iframe's height to content?

I am trying to adjust the height of an iframe to its content. The iframe will be added dynamically by JavaScript, meaning JavaScript has to deal with the element's properties as well:
let iframe = document.createElement("iframe");
iframe.src = "https://en.wikipedia.org/";
document.getElementById("foo").appendChild(iframe);
iframe.onload = function() {
iframe.style.height = "600px";//<-- Does work, why?
resizeIframe(iframe);//<-- Does not work
//iframe.style.height = iframe.contentWindow.document.body.scrollHeight + "px"; //<-- Does not work (when uncommented)
}
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
<div id="foo">
<!-- Iframe to be inserted in here -->
</div>
JSFiddle
Does anyone happen to know what I could do to make this work? I found the following solution and applied it to the code available above:
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
Source
The JavaScript function might (although in this example it would not) work for a plain HTML generated <iframe>, when it comes to a JavaScript generated <iframe>, it does not seem to work. Am I doing something wrong or should I use any alternative method?
Edit: I am using ASP.Net MVC, my project contains the following code in the view:
MyView.cshtml:
<div class="my-class text-center">
<span>
For testing purpose only, this elements has been added. Functionality:
</span>
<br />
<button id="loadiframe" class="btn btn-lg btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">
Load iframe
</button>
</div>
When the button is clicked, it should insert/add an iframe element to the .modal-content part of a Bootstrap Modal:
myscript.js:
function foobar() {
let iframe = document.createElement("iframe");
iframe.src = "/home";
$(".modal .modal-content").html(iframe);
iframe.onload = function () {
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
}
}
$(document).ready(function() {
$("button#loadiframe").on("click", function () {
foobar();
});
});
This does seem to add the <iframe>, but not adjust the height. Would anyone happen to know how I could fix this problem? This would be all happening on the same domain as I am referring to the "home" controller which can be found within my project and which is assigned to my <iframe> source attribute (see code above).

Replace a hyperlink with an iframe

I am trying to replace internal links:
<div class="activityinstance">
activity
</div>
to become:
<div class="activityinstance">
<iframe src="http://website.com/hvp/view.php?id=515512">
activity
</iframe>
</div>
I have been able to replace just the text with an iframe using jquery.
https://codepen.io/alanpt/pen/mWJvoB
But this is proving to be quite hard.
Another difficulty is that it needs to only be links with hvp in the address.
I appreciate any help - thanks.
$('body').ready(function(){
$('.activityinstance a').each(function(){ // get all the links inside the .activeinstance elements
var $this = $(this); // ...
var $parent = $this.parent(); // get the parent of the link
var href = $this.attr('href'); // get the href of the link
if(href.indexOf('/hvp/') == -1) return; // if the href doesn't contain '/hvp/' then skip the rest of this function (where the replacement happens)
$this.remove(); // remove the link as I don't see any reasong for it to be inside the iframe
$parent.append('<iframe src="' + href + '"></iframe>'); // add an iframe with the src set to the href to the parent of the link
});
});
A sample of:
<div class="activityinstance">
activity
</div>
[Because of a fact that having HTML inside of an IFRAME tags has no bearing, and is a complete waste of bytes, we will leave it out. And because this solution doesn't need wrappers, we'll stick to the good old (plain and clean) JavaScript].
The snippet:
[].slice.call(document.links).
forEach(
function( a ) {
if( a.href.match(/hvp/) ) {
a.outerHTML = "<iframe src=" + a.href + "><\/iframe>"
}
} );
will result in clean HTML such as:
<div class="activityinstance">
<iframe src="http://website.com/hvp/view.php?id=515512"></iframe>
</div>
...of course, without indentations and unnecessary white-spaces.
$('a').replaceWith(function () {
var content = this;
return $('<iframe src="about:blank;">').one('load', function () {
$(this).contents().find('body').append(content);
});
});

is(:hover) alternative for ie & firefox

I a have a menu, which on rollover shows a div which is not a child of the menu and when you roll off it hides that div again. The div is placed directly below the menu item, mimicking a submenu.
the html looks something like this -
Here is my menu -
<div id="nav">
<ul>
<li class='with_panel'>
<span id='panel1' class='current'><img src='theImage' /></span>
</li>
<!-- more list items -->
</ul>
</div>
In an unrelated div, I have this -
<div id="panels">
<div style="" id="panel1_panel" class="panel">
<img src="myImage.png">
</div>
<div>
I have some jquery that shows and hides the related panel when you rollover the li -
$("#nav .with_panel").mouseenter(function(){
var id = $(this).find("span").attr("id");
$(".panel").removeClass("open");
$panel = $("#" + id + "_panel");
$panel.addClass("open");
$img = $(this).find("span img");
$img.addClass("on");
var hide = function(){
if(!$panel.is(":hover")){
$img.removeClass("on");
$panel.removeClass("open");
}
}
$panel.mouseleave(hide);
$(this).mouseleave(hide);
})
This only seems to work in Chrome, and I'm fairly certain it's due to ie & Firefox not recognising .is(":hover").
I can't change the html structure, only the javascript. So I'm struggling on getting it to work cross browser. Any ideas?
The following code gives you 200 ms timeout (hide_to) to leave the menu and enter your panel before hiding it. Works the other way too. If you mouseenter the menuitem or the panel the timeout for the hiding is cancelled, and restarted when the mouse leaves any of them.
$("#nav .with_panel").each(function() {
var id = $(this).find("span").attr("id"),
$panel = $("#" + id + "_panel"),
$img = $(this).find("span img"),
hide_to = null;
var hide = function() {
// start hide timeout
hide_to = window.setTimeout(function () {
$img.removeClass("on");
$panel.removeClass("open");
},200);
};
var show = function() {
// clear hide timeout
window.clearTimeout(hide_to);
if (!$panel.is(".open"))
{
// open panel, only if it is not open already
$(".panel").removeClass("open");
$panel.addClass("open");
$img.addClass("on");
}
};
$(this).mouseenter(function() {
show();
}).mouseleave(function() {
hide();
});
$panel.mouseenter(function() {
show();
}).mouseleave(function() {
hide();
});
});
Try mouseover instead of mouseenter and mouseout instead of mouseleave.
For example:
$("#nav .with_panel").mouseover(function(){
var id = $(this).find("span").attr("id");
$(".panel").removeClass("open");
$panel = $("#" + id + "_panel");
$panel.addClass("open");
$img = $(this).find("span img");
$img.addClass("on");
var hide = function(){
if(!$panel.is(":hover")){
$img.removeClass("on");
$panel.removeClass("open");
}
}
$panel.mouseout(hide);
$(this).mouseout(hide);
})
It appears that .is(":hover") is actually broken for all browsers, as of jQuery 1.9.1. Bummer. The following is tested with FF, IE10, and Chrome (sorry don't have Opera) with jQuery 1.9.1. Opera users, please comment on whether this works on Opera.
function isHovered(elt){
var temp = $(elt).parent().find(":hover");
return temp.length == 1 && temp[0] == elt;
}
Then replace
$panel.is(":hover")
by
isHovered($panel[0])
otherwise, leave all your code as is.
fiddle: http://jsfiddle.net/mathheadinclouds/BxL4w/

wanted: simple HTML file that does disclosure triangle <div> hide/reveal

I have a program that produces a text report. I want it to make an HTML report with multiple disclosure triangles, so that when you click a triangle more of the report shows or hides. I am okay with embedding JavaScript inside the file, but I really want it all in a single file, with no additional files. Is there an easy way to do this with modern browsers?
If you don't care about compatibility with Internet Explorer, you could use the html tag: http://www.w3schools.com/tags/tag_details.asp
Its a very quick way to prototype disclosure triangles.
For example:
<details>
<summary>The contents of the summary tag is always visible</summary>
<p>Everything else inside the details tag will be hidden in a disclosure triangle</p>
</details>
The simplest way is something like this:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<style>.wrapper div { display:none;}</style>
<script>
$(function() {
$('.wrapper h2').click(function() { $(this).next().toggle();});
});
</script>
</head>
<body>
<div class="wrapper">
<h2>Example header 1</h2>
<div>bodytext 1</div>
</div>
<div class="wrapper">
<h2>Example header 2</h2>
<div>bodytext 2</div>
</div>
<div class="wrapper">
<h2>Example header 3</h2>
<div>bodytext 3</div>
</div>
</body>
</html>
I have made a simple working example here: http://jsfiddle.net/NXuQt/1/
It isn't pretty but should give you the simple template you need.
Note that in this solution, the entire header is click-able... I figure adding an image and changing it as part of the click event is something you can take care of yoruself, otherwise let me know :)
Note: The javascript is based on the inclusion of the jQuery library.
EDIT: I updated the answer to copy/paste ready working code, the reason you couldn't make it work as it was, was because i had only taken the essentials from the fiddle example. The fiddle automatically ran the click handler initialization at DOMready, which the updated example now has built in :)
With straight HTML, no. That's not what it's for. You will need to use a scripting language, either JavaScript or VBScript, most likely.
This is a script I've used in the past (not mine, but I don't have the URI of the original):
var timerlen = 5;
var slideAniLen = 250;
var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();
function slidedown(objname)
{
if(moving[objname])
return;
if(document.getElementById(objname).style.display != "none")
return; // cannot slide down something that is already visible
moving[objname] = true;
dir[objname] = "down";
startslide(objname);
}
function slideup(objname)
{
if(moving[objname])
return;
if(document.getElementById(objname).style.display == "none")
return; // cannot slide up something that is already hidden
moving[objname] = true;
dir[objname] = "up";
startslide(objname);
}
function startslide(objname)
{
obj[objname] = document.getElementById(objname);
endHeight[objname] = parseInt(obj[objname].style.height);
startTime[objname] = (new Date()).getTime();
if(dir[objname] == "down")
{
obj[objname].style.height = "1px";
}
obj[objname].style.display = "block";
timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
}
function slidetick(objname)
{
var elapsed = (new Date()).getTime() - startTime[objname];
if (elapsed > slideAniLen)
{
endSlide(objname)
}
else
{
var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
if(dir[objname] == "up")
d = endHeight[objname] - d;
obj[objname].style.height = d + "px";
}
return;
}
function endSlide(objname)
{
clearInterval(timerID[objname]);
if(dir[objname] == "up")
obj[objname].style.display = "none";
obj[objname].style.height = endHeight[objname] + "px";
delete(moving[objname]);
delete(timerID[objname]);
delete(startTime[objname]);
delete(endHeight[objname]);
delete(obj[objname]);
delete(dir[objname]);
return;
}
function toggleSlide(objname)
{
if(document.getElementById(objname).style.display == "none")
{
// div is hidden, so let's slide down
slidedown(objname);
}
else
{
// div is not hidden, so slide up
slideup(objname);
}
}
You would assign a call to toggleSlide() to the onclick() event of the element you want to toggle.
CSS:
.hidden {
display: none;
}
Javascript:
function createSection(section, hidden) {
var triangle = section.children[0]; // assumes the triangle image is the first child of a section (see HTML)
var contents = section.children[1];
triangle.onclick = function() {
if (contents.className.indexOf("hidden") != -1) { // the section is hidden
contents.className = contents.className.replace("hidden", "");
} else { // the section wasn't hidden
contents.className += " hidden";
}
}
if (hidden) {
contents.className += " hidden";
}
}
// Create the sections when window loads
window.onload = function() {
createSection(document.getElementById("section1"));
createSection(document.getElementById("section2"), true);
}
HTML:
<div id="section1">
<img src="triangle.jpg"></img>
<div>This is the section content</div>
</div>
<div id="section2">
<img src="triangle.jpg"></img>
<div>this section is hidden by default</div>
</div>
Obviously you would have to change some things to your own html file
Well, after some fiddling around, I was able to make a file that does what I want using the switchcontent.js and switchicon.js javascript files I found at http://www.dynamicdrive.com/dynamicindex17/switchcontent2.htm
Here's my code, based on editing down theirs:
<!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" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Drive DHTML scripts- Switch Content Script II (icon based)</title>
<script type="text/javascript" src="switchcontent.js" ></script>
<script type="text/javascript" src="switchicon.js"></script>
<style type="text/css">
/* Specifies title style */
.iconspan{
margin: 3px;
cursor:hand;
cursor:pointer;
font-weight: bold;
}
</style>
</head>
<body>
<span id="faqtable1-title" class="iconspan"></span>
How hot is our Sun?<br/>
<div id="faqtable1" class="icongroup2">
The surface of the Sun is around 5800 Kelvin, while the core reaches over 15 million Kelvin.
</div>
<br>
<span id="faqtable2-title" class="iconspan"></span>
How big is our Sun in terms of mass? <br/>
<div id="faqtable2" class="icongroup2">
The contains more than 99.8% of the total mass of our Solar System.
</div>
<script type="text/javascript">
var faqtable=new switchicon("icongroup2", "div")
faqtable.setHeader('▼', '▶') //Set header HTML
faqtable.collapsePrevious(false) //Allow more than 1 content to be open simultanously
faqtable.setPersist(true, 7) //Enable persistence to remember last switch content states for 7 days
faqtable.init()
</script>
</body>
</html>
It looks like this when closed:
▶ How hot is our Sun?
▶ How big is our Sun in terms of mass?
And this when opened:
▼ How hot is our Sun?
The surface of the Sun is around 5800 Kelvin, while the core reaches over 15 million Kelvin.
▼ How big is our Sun in terms of mass?
The contains more than 99.8% of the total mass of our Solar System.

Clone a page in a popup with dom included

is it possible to clone an page, javascript and elements in a new popup?
I want to create a popup of a div used like a box of content, all is loaded in javascript
something like
var popup=window.open('', '_blank');
popup.document = this.document;
popup.document.close();
Thanks for your help
I have no idea why you would want to open a copy of the current window and then close it... But here you go:
if(window.name != 'mypopup') {
window.open(document.location.href,'mypopup');
} else {
window.onload = self.close();
}
** Note the window name check.. without it you would just get endless progressoin of windows opening...
<script type="text/javascript">
function popdiv(thediv) {
popwidth = thediv.width;
popheight = thediv.height;
popargs = 'width=' + popwidth + ', height=' + popheight;
popcontents = thediv.innerHTML;
thewindow = window.open('#', 'mypopup', popargs);
thedocument = thewindow.document.open();
thedocument.write = popcontents;
thedocument.close();
}
</script>
<div onclick="popdiv(this);">
Hello,<br />is it possible to clone an page, javascript and elements in a new popup?<br />
<br />I want to create a popup of a div used like a box of content, all is loaded in javascript <br />
Thanks for your help</div>

Categories