Kevin Mamaqi
Kevin Mamaqi

Reputation: 355

Modify HTML element before it loads with Jquery or JS (or is seen)

I'm trying to modify the src of an image for specific pages, like this one: http://oasysgp.kevinmamaqi.com/marina/.

The problem is that the logo changes just after the original one appears. I am using the following code:

jQuery(document).ready(function($){
    /* Cambiar el logotipo para las páginas de CPI */
    if( $('body').hasClass('page-id-18') || $('body').hasClass('page-id-445')) {
        $('#logo').attr("src","/wp-content/uploads/2016/07/oasispci.png");
    }
});

Is possible to load the other image before?

Upvotes: 1

Views: 2509

Answers (2)

Haresh Vidja
Haresh Vidja

Reputation: 8496

jQuery(document).ready() is always called after dom is loaded.

The best way, implement it in CSS code. by set background in a instead of load in image tag

CSS looks like this

a.logo
{
    background: url('/wp-content/uploads/2016/07/logo-oasis.gif');
    display: inline-block;
    height: 56px !important;
    width: 223px  !important;
    margin-top: 24px  !important;
}

body.page-id-18 a.logo,  body.page-id-445 a.logo
{
    background: url('/wp-content/uploads/2016/07/oasisre.png') !important;
}

Your HTML code for logo part is something like this

<a href="http://oasysgp.kevinmamaqi.com/" class="logo">
</a>

Upvotes: 1

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

The problem with you code is that you wait for all HTML to load including the img tags, before replacing src.

The easiest way around this is to simply not put an image in src from the server and then start loading on the front-end:

jQuery(document).ready(function() {
  jQuery("img").each(function(i, el) {
    jQuery(el).attr("src", /*Real image here*/ "https://placeholdit.imgix.net/~text?txtsize=60&txt=SO&w=100&h=100");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />

Upvotes: 1

Related Questions