简体   繁体   中英

How can I ensure an image is downloaded and shown before a HREF fires?

I have this code:

function Imagehover(obj,img){               
    jQuery("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png");            
}
function Imageclick(obj,img){                               
    jQuery("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png");        
}
function Imageout(obj,img){                                                                     
    jQuery("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png");                                
}

<a href="<?php echo JURI::root(); ?><?php echo $langsefs->sef;?>"><img id="<?php echo $langsefs->sef;?>flag" style="height: 40px;margin-right: 10px;width: 47px;" src="<?php echo JURI::root(); ?>/templates/codecraft.gr/images/<?php echo $langsefs->sef; ?>_flag.png" onclick="Imageclick(this,'<?php echo $langsefs->sef; ?>_flag_pressed')" onmouseout="Imageout(this,'<?php echo $langsefs->sef; ?>_flag')" onmouseover="Imagehover(this,'<?php echo $langsefs->sef; ?>_flag_over')" alt="<?php echo $langsefs->sef; ?>"/></a>

But when ever I click the flag, the image dissapears and then the redirection of href executes to the new page. When I remove the onclick event of the image

function Imageclick(obj,img){                               
    //jQuery("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png");      
}

The image doesn't disappear. So I think that the onclick event fires and tries to get the image from the server, but because the href is also executed the image doesnt have the chance to come to the user's browser because the page redirection has begun.

How can I ensure that the image is downloaded to the user's browser and then make the redirection, withoun needing to remove the href attribute?

you can use event.preventDefault() :

If this method is called, the default action of the event will not be triggered.

$('a').click(function(e){
   e.preventDefault();
   var href = $(this).attr('href');
   $("#"+obj.id).attr("src","<?php echo $this->baseurl ?>/templates/codecraft.gr/images/"+img+".png").promise().done(function(){
      window.location = href;
   })        
})

Return false from the event handlers to prevent the default behavior. You may need to put an location redirect in each handler after the image is replaced if you want the page address to change immediately afterword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM