Wrapping a script in a call function - javascript

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.

Related

How to get the image click on Froala Editor

I want to get the .click of the image on Froala Editor to create a customize function, for that I want to get the image I have selected in the Froala Editor.
I have Tried a couple of methods for this.
1.froalaEditor.click function:
$('#froala_editor').on('froalaEditor.click', function(e, editor, clickEvent) {
console.log(clickEvent.toElement);
});
2.Custome jQuery function
$.extend({
IFRAME: function (s) {
var $t = $('.campaign-create-sec').find('iframe');
if (typeof s !== 'undefined') {
return $t.contents().find(s);
}
return $t;
}
});
$('#froala_editor').on('froalaEditor.initialized', function (e, editor) {
$.IFRAME('body').on('click', function (e) {
console.log(e.target);
});
});
In the above, both cases I am getting all the other elements other than <img> and <video> of what I tested, so Is there any other way for me to get the click even for an image in Froala Editor.
A fiddle for you to check, any help will be appreciated.
You can try this.
var monitor = setInterval(function(){
var iframe_found = $('iframe').length;
console.log('iframe_found '+iframe_found);
if (iframe_found) {
clearInterval(monitor);
$('iframe').contents().find("img").click(function(){
$(this).css('border','2px solid #090');
console.log('got that!');
});
}
}, 100);
Here is the working fiddle.
setInterval() : For checking iframe presence after page load. iframe may only load after the page data is loaded & in your case its from a editor plugin, may take some time surly to load.
$('iframe').length; : Confirms presence of iframe.
clearInterval() : For destroying the setInterval(), so avoids multiple checking again for iframe.
And, at last we are finding required img tag.
Try... Have a nice day.

JS load image on click

I need to load an image, js need to get link url and print this image on screen.
But it is not working.
What is wrong with my script? what can I do to make it work and improve it?
html
<div id=img></div>
<div id=loading></div>
<a href=http://png-5.findicons.com/files/icons/1580/devine_icons_part_2/128/my_computer.png class=postmini>Open image 1</a>
<br>
<a href=http://www.iconshock.com/img_jpg/BETA/communications/jpg/256/smile_icon.jpg class=postmini>Open image 2</a>
js
$(function() {
$(".postmini").click(function(){
var element = $(this);
var I = element.attr("href");
$("#loading").html('<img src="loader.gif" align="absmiddle"> loading...');
$("#loading").ajaxComplete(function(){}).slideUp();
$("#img").append(I);
});
});
https://jsfiddle.net/u6j2udzb/
and this loading div, what I need to do to make it work properly?
You are missing a lot and have a lot you don't need. I have commented out where you don't need items. In particular you don't need a loading because the image will be there before they see that. However, if you do want it still, you should be loading it underneath the image you are loading. So it gets covered by the image. I can update it with that if you'd like.
What you are missing is actual code to turn the href into an image source and you are not removing the default action of the anchor tag so it doesn't try loading a new page when clicked.
$(".postmini").click(function(event){
event.preventDefault();
var element = $(this);
var I = element.attr("href");
//$("#loading").html('loading...');
//$("#loading").ajaxComplete(function(){}).slideUp();
// remove old image if it is already there.
$("#img").empty();
// create variable holding the image src from the href link
var img = $("<img/>").attr("src", I)
$("#img").append(img);
});
https://jsfiddle.net/3g8ujLvd/
You just have to insert an img tag into your "display div" on click on the link... to load the image... (btw your syntax errors are terrible... you have to use quotes for attributes^^)
like this for example :
$('.postmini').on('click',function(){
//do something
});
Check this : https://jsfiddle.net/u6j2udzb/8/
(done quickly for example)
Hope it helps
You are not running an ajax script. ajaxComplete is only fired after an ajax script completed.
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
You should ad an ajax script and than ajaxComplete will run if you registered the ajaxComplete method.
At the moment you're just placing the text from the "href" attribute on the link into the div. You need to either create an image or use the link provided as a background.
The quickest way to see this is to change make this change:
var element = $(this);
var I = element.attr("href");
$("#loading").html('<img src="loader.gif" align="absmiddle"> loading...');
$("#loading").ajaxComplete(function(){}).slideUp();
// $("#img").append(I);
$("#img").html("<img src='"+I+"' />");
$('.postmini').on('click',function(e){
e.preventDefault();
$('#loading').html('<img src="'+this.href+'">').children('img').one('load',function(){$(this).parent().slideUp('slow');});
});
Noticed I used on instead of click this allows you to use this.href rather than a more lengthy $(this).attr('href'). I also used .one on a child image element to find out if the image has loaded.
But I've just realised that this is useless because you want to have a loader. Ma bad.
$('.postmini').on('click',function(e){
e.preventDefault();
//best have the loader.gif showing on default before the load is complete.
var img=$('<img class="loadedImage">');
img.src=this.href;
//img.css({display:none;});//remove this if you've enter CSS .loadedImage{display:none;}
$('#loading').append(img).slideDown('slow',function(){$(this).children('.loadedImage').one('load',function(){$(this).fadeIn('slow');$(this).siblings('img[src="loader.gif"]').hide();});});
});
This method is what you're looking for. Basically you want to click the link, stop the default action of going to the link, make a new image element and set the src, make sure it's hidden before load, add the new image element to loading, slide up parent loading, check for load and fade in :)
Try and run this simple snippet
$('#myButton').click(()=>{
let imgUrl = $('#imgUrl').val();
$.get(imgUrl)
.done(() => {
$('img').attr('src', imgUrl);
$('#imgText').text('');
})
.fail(() => {
$('#imgText').text('Image does not exist');
$('img').attr('src', '');
})
})
img {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Image url: <input type="text" id="imgUrl" value="https://upload.wikimedia.org/wikipedia/commons/7/75/Woman_mechanic_working_on_engine_%28cropped%29.jpeg"><br>
<button id="myButton" type="button">click here to load image</button>
<div id="imgText"></div>
<img>

Can't detect IMG jquery error event when using handlebars.js. How can I fix these broken images?

I'm having trouble detecting the error event of an image with a broken source.
The image is created in handlebars like this:
<img src="{{image}}" alt="the image">
I'm trying this code:
console.log('first log');
$('img').one('error', function() {
console.log('image error detected');
this.src = "<my other image path here>";
});
I can't get my console.log, unless I hit "back" and then "forward" in the chrome browser navigation bar. The replacement of 'this.src' also works if I hit "back" and then "forward".
I've tried many things like .load or putting this code in document ready, etc.
When I view the console, I see the two GET's for the two images on this page, followed by the "first log" above. So, the images are hitting the error event well before my listener has been binded. Or something like that maybe...
Any suggestions?
Finally got this working. I'm sure there is a better way, but this is what did it for me:
if ($('[data-path="/blahblah"]').length) {
$('.myClass img').each(function() {
var image = $(this);
if (image.context.naturalWidth == 0 || image.readyState == 'uninitialized') {
image.unbind('error').attr("src", "<placeholder src here>");
}
})
}

.removeClass not functioning within .replaceWith

I'm trying to make a button that will hide a specific -- and then replace it with another hidden . However, when I test the code, everything fires correctly except for the .removeClass which contains the "display: none."
Here is the code:
<script type="text/javascript">
$(document).ready(function(){
var webform = document.getElementById('block-webform-client-block-18');
var unmarriedbutton = document.getElementById('unmarried');
var buyingblock = document.getElementById('block-block-10');
$(unmarriedbutton).click(function () {
$(buyingblock).fadeOut('slow', function() {
$(this).replaceWith(function () {
$(webform).removeClass('hiddenbox')
});
});
});
});
</script>
The CSS on 'hiddenbox' is nothing more than "display: none.'
There is a with the id of unmarried, which when clicked fades out a div and replaces it with a hidden div that removes the class to reveal it. However, the last part doesn't fire -- everything else does and functions properly. When I look at in the console too, it shows no errors.
Can someone please tell me where the error is? Thanks!
Edit: I may be using the wrong function to replace the div with, so here's the site: http://drjohncurtis.com/happily-un-married. If you click the "download the book" button, the the div disappears and is replaced correctly with the div#block-webform-client-block-18. However, it remains hidden.
The function you pass to replaceWith has to return the content you want to replace it with. You have to actually return the content.
I don't know exactly what you're trying to accomplish, but you could use this if the goal is to replace it with the webform object:
$(this).replaceWith(function () {
return($(webform).removeClass('hiddenbox'));
});
NB, use jquery !
var webform = $('#block-webform-client-block-18');
var unmarriedbutton = $('#unmarried');
var buyingblock =$('#block-block-10');
unmarriedbutton.click(function () {
buyingblock.fadeOut('slow', function() {
$(this).replaceWith( webform.removeClass('hiddenbox'));
});
});
Was too fast, i believe it's the way you select your object (getelementbyid) then you create a jquery object from it... -> use jquery API

How do I use colorbox to show hidden divs on my page without hardcoding?

I'm using Colorbox to show the html content of hidden divs on my page. I can get this to work perfectly with the following:
$("a.colorbox").colorbox({width:"600px", inline:true, href:"#344"});
This will show the div with the ID of 344.
However, because I'm trying to build a scalable and dynamic page with WordPress, I want to be able to grab the ID of my divs through a function, rather than hard code them in the jquery call.
I modified Jack Moore's example:
$("a[rel='example']").colorbox({title: function(){
var url = $(this).attr('href');
return 'Open In New Window';
}});
so that it looks like this:
$(".colorbox").colorbox({width:"600px", inline:true, href:function(){
var elementID = $(this).attr('id');
return elementID;
}});
The problem with this is that the href property of the colorbox function is looking for a string with a # mark infront of the ID. I tried various ways of concatenating the # to the front of the function, including the # in the return value, and concatenating the # to the elementID variable. No luck.
I also tried using the syntax in Jack's example (with no luck) so that my return statement looked like this:
return "#'+elementID+'";
I think my basic question is: How do I use colorbox to show hidden divs on my page without hardcoding everything?
Thanks for your help,
Jiert
I didn't really like any of the answers given above. This is how I did it (similar but not quite the same).
I also fully commented it for people a bit new to Javascript and the colorbox plug in.
$(document).ready(function() { //waits until the DOM has finished loading
if ($('a.lightboxTrigger').length){ //checks to see if there is a lightbox trigger on the page
$('a.lightboxTrigger').each(function(){ //for every lightbox trigger on the page...
var url = $(this).attr("href"); // sets the link url as the target div of the lightbox
$(url).hide(); //hides the lightbox content div
$(this).colorbox({
inline:true, // so it knows that it's looking for an internal href
href:url, // tells it which content to show
width:"70%",
onOpen:function(){ //triggers a callback when the lightbox opens
$(url).show(); //when the lightbox opens, show the content div
},
onCleanup:function(){
$(url).hide(); //hides the content div when the lightbox closes
}
}).attr("href","javascript:void(0)"); //swaps the href out with a javascript:void(0) after it's saved the href to the url variable to stop the browser doing anything with the link other than launching the lightbox when clicked
//you could also use "return false" for the same effect but I proffered that way
})
}
});
And this is the html:
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
I think it would work with multiple lightboxes on the one page but I haven't tested it with that.
I'm facing the same issue. What does your html look like? meaning, how did you structure your "divs"
Mine looks like this:
Javascript:
<script>
$(document).ready(function () {
$("a.colorbox").colorbox({ width: "50%", inline: true, href: function () {
var elementID = $(this).attr('id');
return "#" + elementID;
}
});
});
</script>
And the html looks like (I tried changing the display:none):
<a class='colorbox' href="#">Inline HTML</a>
<div style="display:none">
<div id="pop">
This data is to be displayed in colorbox
</div>
</div>
return "#" + elementID;
will have the desired effect as David says.
This is the way I got it to work
HTML: (taken from the example in one of the answers)
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
Javascript:
$('a.lightboxTrigger').click(function(){
var ref = $(this).attr("href");
$.colorbox({ html: $(ref).html() });
$.colorbox.resize();
});

Categories