execute code AFTER Recaptcha.reload() is finished - javascript

I have a function below which is called to reload a recaptcha image. It works, reloads the image but won't do anything after that. Basically the form is small that has this recaptcha on it so I've shrunk it and allowed for clicking to enlarge and all that. If the person presses "get another captcha" which calls reloadCAP() it checks to see if it has the class of being the larger image. if it does i need it to add that class and css back to the elements AFTER the new image has loaded but I can't seem to get it to work. Any ideas?
function reloadCAP() {
if($("#recaptcha_widget img").hasClass('largecap')) {
Recaptcha.reload();
$("#recaptcha_widget img").addClass('largecap');
$('#recaptcha_image').css('height', '62px');
} else {
Recaptcha.reload();
}
}
here's the html for this:
<div id="recaptcha_widget" class="formRow" style="display:none;">
<span class="f_label">Enter Words Below:</span>
<input type="text" class="setWidth" id="recaptcha_response_field" name="recaptcha_response_field" />
<div class="cantread">
<strong>Can't read this?</strong><br />
Get another CAPTCHA
</div>
<div id="recaptcha_image"></div> <!-- image loaded into this div -->
<div class="clear"></div>
<span class="smalltext">(click to enlarge)</span>
<br clear="all" />
</div>
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6LfzMMwSAAAAADV6D04jDE6fKwrJ57dXwOEW-vY3&lang=en"></script>

$("#recaptcha_widget img").one('load',function(){
$("#recaptcha_widget img").addClass('largecap');
$('#recaptcha_image').css('height', '62px');
});
This will put a one time only listener on the load event of the image that you are reloading and then executes the folowing code.
I used .one() instead of .load() here because you don't want to attach a new listener every time you call reloadCAP()
Edit
Ok, so here's what I believe the issue is. When you call Recaptcha.reload() it is removing the <img /> and replacing it with a new one. So when we are trying to attach the event it is getting removed as the image gets removed.
What you need to do is place the class largecap on the recaptcha_image div and modify your css style to look like
.largecap img {
height: whatever;
width: whatever;
}

Not the ideal solution, but you could put the addClass code above Recaptcha.reload() and just delay it by a second or two.
Hope that helps.

It sounds like what you actually need is custom theming such that you can style the captcha/image/etc exactly as needed: https://developers.google.com/recaptcha/docs/customization
If you do want to stick to your current implementation, you can hook into Recaptcha's built in (and undocumented) callback functions prior to calling Recaptcha.create().
//Called after Recaptcha.reload() is finished loading
Recaptcha._alias_finish_reload = Recaptcha.finish_reload;
Recaptcha.finish_reload = function (challenge, b, c) {
//Call original function that creates the new img
Recaptcha._alias_finish_reload(challenge, b, c);
$("#recaptcha_widget img").toggleClass('largecap', true);
}
//Called when the initial challenge is received on page load
Recaptcha._alias_challenge_callback = Recaptcha.challenge_callback;
Recaptcha.challenge_callback= function () {
//Call original function that creates the new img
Recaptcha._alias_challenge_callback();
$("#recaptcha_widget img").toggleClass('largecap', true);
}
The reason you're even having this problem is because Recaptcha destroys and creates a new img everytime it reloads, so the styling you added manually will be lost.

Related

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>

javascript to load image source keeps the page blinking

I am new to Javascript,
I try to make a simple program which changes image source on button click.
the image is being loaded but immediately deleted.
it works only if I call the image source loading function from the onload event of the body.
but than the result is wromg:
it loads all the page with the wrong image source and than call the onload function -> resulted in page that blinks twice until fully loaded.
My final goal is to allow one initial images loading and than change images on button click from javascript (not calling the server). Thanks in advance
function load() {
document.getElementById("mainImg").src = 'Koala.jpg';
}
<button type="submit" name="btn0101" value="btn" onclick="load()" >
<img src="iconUnavail.png" id="mainImg" />
</button>
I assume you are trying to preload images. This is how you do that.
var myImage = new Image(100, 100)
myImage.src = "mainImg"
Then when you are ready (button click), just swap out the src and the image will appear immediately.
That said, a better way would be to use sprites.
What you can do is bind your event to the onclick event in the button itself like so
jsFiddle https://jsfiddle.net/a3pv8j71/1/
Html
<img id="mainImg" src="http://www.squirrelsandmore.com/media/wysiwyg/feline_cat_img.jpg">
<button type="submit" onclick="changeImage()">Change img
</button>
Javascript
function changeImage() {
document.getElementById("mainImg").src = 'http://photos.jibble.org/Experimental/Flying%20Cat/IMG_4821%20Flying%20cat%20.JPG';
}
The "submit" call in your <button> will force the page reload - try removing that.

Why is this java script not working?

In reference to this post: How to display loading image while actual image is downloading
I have the following code, but for some reason I cannot get the #loader_img to hide. I would also like to add a preloader because the large image is really heavy, but I want to keep it simple if possible since I am new to javascript...
<img id="loader_img" src="img/ajax-loader.gif" alt="Loading..." />
<div class="magnifier" style="height: 584px; width: 467px; margin: 20px;">
<div class="maglens">
<img id="imgload" src="img/largeimage.jpg" />
</div>
</div>
JS:
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
$("#imgload").on('load', function(){
// hide/remove the loading image
$("#loader_img").hide();
});
Any help will be much appreciated! Thank you!
The image's load event is almost certainly firing before you hook the event. Since it's already fired when you hook the event, you never see it occur.
Also, you start out hiding the image (#imgload), but you never then show it.
To ensure that you get the event, you have to hook load before setting the image's src.
Alternately, you can use the image's complete property to know if it's already been loaded:
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
var img = $("#imgload");
if (img[0].complete) {
imageDone();
} else {
img.on('load', imageDone);
}
function imageDone() {
// hide/remove the loading image
$("#loader_img").hide();
// And show the image!
img.show();
}
You also have to ensure that the code above runs after the elements have been created. The best way to do that is to put your script tag containing the code after the elements it refers to in the HTML (usually putting it just before the closing </body> tag works well). As a second-best solution, you can use jQuery's ready function. Either way, you'll still need to handle the possibility the load event has already fired.
Here's an example:
<div id="loader_img">Loading</div>
<div class="content">
<img id="imgload" src="http://i.stack.imgur.com/rTQCa.jpg?s=512&g=1" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function() { // Avoid creating globals
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
var img = $("#imgload");
if (img[0].complete) {
console.log("Complete");
imageDone();
} else {
console.log("Wait for load");
img.on('load', imageDone);
}
function imageDone() {
console.log("Loaded");
// hide/remove the loading image
$("#loader_img").fadeOut();
// And show the image!
img.show();
}
})();
</script>
Hi you may use this method. jQuery.ready()I have tried on my computer and it's okay this way.
BTW, you forgot to let the "imgload" show again.
// show loading image
$("#loader_img").show();
$("#imgload").hide();
// main image loaded ?
$("#imgload").ready(function(){
// hide/remove the loading image
$("#loader_img").hide();
$("#imgload").show(); // show the loaded img again
});
I think that the script is executed before the DOM is loaded.
Take your script and put it between:
$(function () {
//Your code here
});
This will insure that the code will run after the DOM is loaded.

Using Document Ready on Click Event

I am still new to javascript.
I have an application that has two buttons on the page. One is a cpu_vs_player button that displays one game and the other is a player_vs_player button that displays a different game. The problem is that all the code is located in one application.js file. There is no need to load the player_vs_player on $(document).ready(function(){}); if I were to play cpu_vs_player.
Any ideas on how I can get them to load only if I chose that game? (I am only using one route with all the information being hidden / shown based on the click).
The document.ready is nothing more than the moment after the page has rendered and the document needs to be populated with event listeners. Frankly there are multiple way of skinning this cat.
You can either do the jQuery way where you keep javascript and HTML divided:
<button id="button1">cpu_vs_player</button>
<button id="button2">player_vs_player</button>
And for JavaScript:
Assuming you have a function for each gameplay:
function cpu_vs_player() {
// start the game
}
function player_vs_player() {
// need another player
}
Add event listeners the jQuery way:
$(document).ready(function() {
$("#button1").click(function() {
cpu_vs_player();
});
$("#button1").click(function() {
player_vs_player();
});
});
OR you could use the method #Techstone shows you, though you could do it more direct. It all works though.
<button onclick="javascript:cpu_vs_player();">cpu_vs_player</button>
<button onclick="javascript:player_vs_player();">player_vs_player</button>
Adding another option you can apply
In Javascript:
var Main = {
cpu_vs_player: function() {
alert("start cpu_vs_player");
},
player_vs_player: function() {
alert("start player_vs_player");
}
}
In your HTML:
<button onclick="javascript:Main.cpu_vs_player();">cpu_vs_player</button>
<button onclick="javascript:Main.player_vs_player();">player_vs_player</button>
And yes, there is more ... ;-)
image that your two button and js definition like below
function LetsRock(Playmate) {
....
}
<input type='button' value='cpu_vs_player' id='cpu_vs_player' onclick='javascript:LetsRock(this.id);' />
<input type='button' value='player_vs_player' id='player_vs_player' onclick='javascript:LetsRock(this.id);' />
Try to use the function with parameters (i.e. 0 to cpu v/s player, 1 to player v/s player), and send from the menu page to the $(document).ready(function(){});

I need to update my page using Anchor (#) in URL

index.php
<html>
<head>
<title>My Title</title>
<script type="text/javascript">
function getLink(data) {
document.getElementById("box").innerHTML="This is "+data;
}
</script>
</head>
<body>
Home<br />
Profile<br />
Message<br />
Setting<br />
<hr />
<div id="box"></div>
</body>
</html>
Output
Home
Profile
Message
Setting
This is Home
As the code says my Div contents updated when i click any of the link but the problem is that when user goes back by clicking Back Button of Browser the content of my Div donot changes.
I want that either user Goes Back, Goes Forward or he directly puts the path in the address bar www.*****/index.php#profile the content of my Div should be change.
Note
I used document.location.hash to get the value of hash like this :
<head>
<script>
var hashValue=document.location.hash;
alert(hashValue);
</script>
</head>
but it works only when user goes back and then refresh the page
Plz help me how can i achieve this :(
You need to use hashchange event:
function hash_changed() {
var data = document.location.hash.substr(1);
var box = document.getElementById("box");
if (data) {
// inner page
box.innerHTML="This is " + data;
}
else {
// homepage
box.innerHTML = "";
}
}
window.onhashchange = function () {
hash_changed();
};
window.onload = function () {
hash_changed();
};
Also when you are using hashchange event, there is
no need to set onclick for your links:
Home
Profile
Message
Setting
When user click on a link, the hash automatically changes (with href attribute of link),
and hashchange event get fired.
Check DEMO here.
First Time
When a user come to your page for the first time with a hash:
http://fiddle.jshell.net/B8C8s/9/show/#message
We must show the wanted page (message here), so we must run hash_changed() function
we declare above, at first time. For this, we must wait for DOM ready or window.onload.
Check the HTML5 history API. It allows you to work with the browser history
HTML5 history api
$(window).on('hashchange', function() {
alert(location.hash);
});
or window.onhashchange event if you don't want to use jQuery
If you're going to be using AJAX, you'll really want to look into using jQuery instead of raw javascript unless your intention is educational. jQuery is just a mainstay of the web now.
If you must use those hashes...
Use jQuery Special Events, and use the hashchange event:
<a href='#home'>Home</a>
Script:
$(window).on('hashchange', function() {
$('#box').html("This is "+event.fragment);
});
However, for your scenario...
You don't need to use those # values at all as you're passing the values in your function arguments anyway according to the code you provided, just do this:
Home<br />
Alternatively (and preferably, as you're using AJAX according to the tags) you can use jQuery and its builtin selector click events which use Event Listeners:
<a href='javascript:void();' class='divLink' id='home'>Home</a><br/>
Script is this easy:
$('.divLink').click(function(){
$('#box').html("This is "+$(this).id());
}

Categories