'Overlay transparent image' jQuery breaks when new class is added - javascript

I found this script HERE to overlay a transparent image over photos that I would like to 'protect' on my site. On images that have hyperlinks, I would like be able to give them a special class and make them accessible.
Here is the original script:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var pixelSource = 'http://static.squarespace.com/static/51c351f0e4b0c89ff2b61cb8/t/52cc3905e4b0167d33cd524e/1389115653884/Transparent.gif';
var useOnAllImages = true;
// Preload the pixel
var preload = new Image();
preload.src = pixelSource;
$('img').live('mouseenter touchstart', function(e) {
// Only execute if this is not an overlay or skipped
var img = $(this);
if (img.hasClass('protectionOverlay')) return;
if (!useOnAllImages && !img.hasClass('protectMe')) return;
// Get the real image's position, add an overlay
var pos = img.offset();
var overlay = $('<img class="protectionOverlay" src="' + pixelSource + '" width="' + img.width() + '" height="' + img.height() + '" />').css({position: 'absolute', zIndex: 9999999, left: pos.left, top: pos.top}).appendTo('body').bind('mouseleave', function() {
setTimeout(function(){ overlay.remove(); }, 0, $(this));
});
if ('ontouchstart' in window) $(document).one('touchend', function(){ setTimeout(function(){ overlay.remove(); }, 0, overlay); });
});
});
</script>
I was told to change this line:
$('img').live('mouseenter touchstart', function(e) {
To this:
$('img').not('.FreeMe').live('mouseenter touchstart', function(e) {
... and give the images I want to be clickable the class of '.FreeMe'.
When I run the script with no changes, the transparent overlays work great. Once I change that line of code and add the special class, all of the images become accessible again and the script no longer works.
HERE is a link to the page I've been working on. The Photographers information at the bottom of the screen is the image I would like to add a hyperlink to.
I have been searching high and low in order to make this work but was unable to find a solution to the problem. I'm very new to Javascript and jQuery, but know just enough in CSS and HTML to be dangerous.
I appreciate any help you all could provide.

You should use the .on() method instead of .live(), since the .live() method can't be chained like other jQuery methods (the params are just the same).
Quoting jQuery's doc on .live():
Use of the .live() method is no longer recommended since later
versions of jQuery offer better methods that do not have its
drawbacks. In particular, the following issues arise with the use of
.live():
• Chaining methods is not supported. For example, $( "a" ).find(
".offsite, .external" ).live( ... ); is not valid and does not work
as expected.
Plus, as said in the comments, as of jQuery 1.7, the .live() method is deprecated.
You an see a working demo with adorable kittens here.

Related

Reprocess code for a dynamically loaded "widget"?

I have the following code that loads a tile, or "widget", in my UI. Occasionally (like on orientation change) I have to redraw the tiles. Some of the content is generated by a script load event. During the redraw, this event is not getting loaded again. How can I accomplish this?
//html
let $elTile = $('<div/>').appendTo($elContainer);
$elTile.load('tiles/' + tile.name + '/' + tile.name + '.html #' + tile.name + '-content');
//javascript
$.getScript('tiles/' + tile.name + '/' + tile.name + '.js');
//css
$('head').append( $('<link rel="stylesheet" type="text/css" />')
.attr('href', 'tiles/' + tile.name + '/' + tile.name + '.css'));
And here is what one of the tile script files looks like:
window.addEventListener("load", function() {
//do some stuff that may need to be called again on orientation change
});
I see from questions like this and this that I probably can't just "unload and reload" the script, so is there another way to process the "tile initialization" script again?
Orientation Change was just an example, I'd like to be able to call the tile init script arbitrarily if possible.
Depending on your device support and requirements, you could do a few things.
One would be to deal with this by also adding orientationchange to your event listener.
$(window).on('load orientationchange', function(){ /* run your code for both*/});
Another option would be to use the resize event.
The former would be device specific as all browsers act differently, as mentioned in this post.
UPDATE:
You can also create an anonymous event based function that you can call at will using your event as the trigger. For example.
$(window).on('myCustomEvent', function(){ /*whatever code you want to run at any time*/});
Then you can trigger such event from any logic point you need:
if ($(window).width() < 1024){
$(window).trigger('myCustomEvent');
}
You can use other events, like "orientationchange"
https://developer.mozilla.org/en-US/docs/Web/Events/orientationchange
Or you can recall the load function like this:
var myFunction = function () {
//do some stuff that may need to be called again on orientation change
};
window.addEventListener("load", myFunction);
window.addEventListener("orientationchange", myFunction);
...
And you can call it again anytime just using myFunction();

Add CSS to DIV in an Iframe

I have an Iframe with id="scorm_object".
<iframe id="scorm_object">...</iframe>
Inside this iframe i have a class called framewrap.
I am trying to add CSS to this class like so:
$(document).ready(function() {
$('#scorm_object').contents().find('.framewrap').css('opacity','.2');
});
but I can't seem to get it to work.
I know there are multiple iframe examples on here, but I am really looking for something nice and simple.
Thanks!
Update: Apologies, I have to make this work without jquery.
I have now tried the following:
var iframe = document.getElementsByTagName('iframe')[0];
iframe.addEventListener("load", function() {
window.frames[0].document.body.style.backgroundColor = "#fff";
});
but I get the :
iframe is undefined
error.
Your are firing the JavaScript when the DOM of the parent document is ready. This is likely to happen before the document in the frame is ready.
Waiting for the load event to fire fixed that when I tested it.
Use $(window).on("load", function() { instead of $(document).ready(function() {.
I think this one will work. Change the CSS after iframe loaded
$('#scorm_object').load(function() {
$('#scorm_object').contents().find('.framewrap').css('opacity','.2');
});
If you want to do it in pure javascript you should do something like this. Create an style element and add necessary styles using textContent property and add that style to the of iframe.
var iFrame = document.getElementById("scorm_object");
var style = document.createElement("style");
style.textContent =
'#framewrap{' +
' opacity: 0.2;' +
'}' +
'h1 {' +
' color: green;' +
'}'
;
iFrame.addEventListener ("load", function () {
iframe.contentDocument.head.appendChild(style);
});
The above method doesn't work with cross-domain.
You check this out window.postMessage

Wrapping a script in a call function

I have a script im currently using, the issue is that i have to add the script directly after every html img tag. So there is the same script in several different places throughout the site. I am wondering if it is possible to wrap this script in a simple function call, and i can just add the function throughout the site instead of the whole script.
EDIT: I should have mentioned. This is a lightbox for a Tumblr theme. photo_{PostID} is valid. photo_{PostID} retrieves the unique photo identifier so the lightbox will display the correct image. The script right now works 100% perfectly fine no doubt about that. I'm looking to turn it all into a simple 1 liner call function to use instead of needing to paste the script after every img tag.
the script is below, thanks.
<script class="inline_embed" type="text/javascript">
var domain = document.domain,
photo_{PostID} = [{
"width": "{PhotoWidth-HighRes}",
"height": "{PhotoHeight-HighRes}",
"low_res": "{PhotoURL-250}",
"high_res": "{PhotoURL-HighRes}"
}];
function event_is_alt_key(e) {
return ((!e && window.event && (window.event.metaKey || window.event.altKey)) || (e && (e.metaKey || e.altKey)));
};
document.getElementById('photo_{PostID}').onclick = function (e) {
if (event_is_alt_key(e)) return true;
window.parent.Tumblr.Lightbox.init(photo_{PostID});
return false;
}
</script>
You tagged this question with [jquery] so I'm going to give an answer using jquery, even though your sample code doesn't use it.
Here's a fiddle:
http://jsfiddle.net/u2f2b5qq/
Given a few images on the page, like this:
<img src="http://placehold.it/250x150">
<img src="http://placehold.it/200x250">
<img src="http://placehold.it/350x150">
<img src="http://placehold.it/150x50">
You can do some action on all of them once the page loads, like this:
$(function() {
$('img').each(function() {
$(this).on('click', function() {
alert('You clicked ' + $(this).attr('src'));
// window.parent.Tumblr.Lightbox.init(this);
});
});
});
What I've done is attach a click handler to every image and alert when it's clicked. You would replace that with your lightbox code.
I don't have a full understanding of how tumblr does its magic with interpolating those values, but I assume you could do something like this for each image. It attaches the Photo data to each image element, and then retrieves it later.
<img src="example.jpg" id="photo_{PostID}" data-width="{PhotoWidth-HighRes}" data-height="{PhotoHeight-HighRes}" data-low_res="{PhotoURL-250}" data-high_res="{PhotoURL-HighRes}" />
and then in the jquery kickoff:
$(function() {
$('img').on('click', function() {
var $img = $(this);
alert('You clicked ' + $img.attr('src'));
window.parent.Tumblr.Lightbox.init({
width: $img.data('width'),
height: $img.data('height'),
low_res: $img.data('low_res'),
high_res: $img.data('high_res')
});
});
});
Give that a shot.

Location attr not relocating on ipad or iphone

I have a few location attrs on my website for a few dynamic drop downs and clickable divs. While testing I saw that they are not working on any ipads or iphones. Is there a reason for this?
They look like this
$('.storyClick').click(function () {
var context = $(this).closest('.storyClick'),
story_id = context.find('.story_id').val();
$(location).attr('href', '/chapters/' + story_id)
});
The updated code? Sure...
$('.storyClick').click(function () {
var context = $(this).closest('.storyClick'),
story_id = context.find('.story_id').val();
location.href = '/chapters/' + story_id;
});
Why are you making a jQuery object out of that?
location.href = '/chapters/' + story_id;
DOM nodes are the only things that should be wrapped in a jQuery object. (Well, ideally, nothing would be, but here we are.)
And you apparently need to handle two events using .on('click touchstart', …), because it’s not a link.

How to detect when -webkit-mask-box-image has downloaded

I generate an mask image on a web server programmatically, then apply it to a HTML element with the following code:
imageToMask.style["-webkit-mask-box-image"] = "url('" + featherURL +"') 100 stretch";
How can I find out when the image comes back and has finished downloading, so that it doesn't just pop onto the page?
You can probably do something similar to what #lonesomeday did in:
jQuery .on() not bound when script inserted into the DOM
Something along these lines:
$('button').click(function() {
var imageToMask = document.createElement('img');
imageToMask.style["-webkit-mask-box-image"] = "url('" + featherURL +"') 100 stretch";
imageToMask.onload = function() {
//Custom behaviour
};
document.body.appendChild(imageToMask);
});

Categories