bharath c bharath c - 7 months ago 11
Javascript Question

have to wait to execute jquery till the service is loaded

i am trying to open the hyper links in a new tab. for loading in a new tab i am using the following code. which will run once and adds target="_blank" in the anchor tags.

<script>
$(document).ready(function(){
alert("ready");
$("a", "#myCustomContent").each(function() {
$(this).attr('target', '_blank');
});
});
</script>


but the jquery is executed before the contents is retrieved from the service call and i cannot open the hyperlinks in a new tab. so i tried using the below code.

$(window).bind("load", function() {
$("a", "#myCustomContent").each(function() {
$(this).attr('target', '_blank');
});
});


here it fails as some of the images or the files fails to load. or it will take more time.

i need to find a way to call the jquery to open the "ahref" tag in a new tab.
thanks in advance

Answer

Without seeing more of the code I'd have a hard time deciphering exactly what the best step would be, but it sounds like you are having images with links load after your code runs. You could always try something that would update the click handler on load:

$('body').on('click', 'a', function(){
    $(this).attr('target', '_blank');
});

Or you could look into a function that checks if your images are loaded and sets a timeout until they are all set.

var changeTarget = function() {
    if ($('body').find('#img')) {
        //do code it's loaded
    } else {
        //repeat in 100 miliseconds
        setTimeout(changeText,100);
    }
}
changeTarget();
Comments