Zahema
Zahema

Reputation: 1415

how to use jquery in included html?

sorry for the title... so i separated the index.html into divs then i called the contant using :

<script>$(function(){$("#work_bunch").load("wb.html"); });</script>

and it works fine but i wont to use jquery on the elements in wb.html i used this in index :

<script type="text/javascript" src="java_scripts/wb_op.js"></script>

what ever i write in the .js file it seems to work fine in the index but i can't select any element in wb.html

for example (if img5 is an element wb.html) :

$("#img5").mouseover(function(){
  $(img5).fadeOut(2000);
});

Upvotes: 1

Views: 80

Answers (5)

Girish
Girish

Reputation: 12127

use delegate method on if content added dynamically

$("#work_bunch").on("mouseover", "#img5", (function(){
  $(this).fadeOut(2000);
});

and typo issue $(img5) to $("#img5")

Upvotes: 1

Zahema
Zahema

Reputation: 1415

here is what i found to be more general solution use

$(window).load(function() {
 // executes when complete page is fully loaded, including all frames, objects and images
});

instead of

$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready
});

because: - The document ready event executes already when the HTML-Document is loaded. - The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images.

Upvotes: 1

Kiba
Kiba

Reputation: 10827

If you are including .js in head tag, then you need to make use document.ready()

$(document).ready(function() {
 $("#img5").mouseover(function(){
  $(this).fadeOut(2000);
  });
});

Upvotes: 1

Jai
Jai

Reputation: 74738

Delegate the event:

$("#work_bunch").on("mouseover", "#img5", function(){
    $(this).fadeOut(2000);
});

When DOM was ready your elements were not there they come into view afterwards so at the time of DOM ready all the events were bound to existing elements. If any element is generated dynamically or put into the view via ajax any event will not be bound to them.

So the solution to cater this issue is to try to delegate the event to the closest static parent whenever possible, although you can delegate to document also but that is way expensive in lookup of that dom elements.

explaining syntax:

$(parentToDelegate).on(event, selector, callbackFn);

Upvotes: 1

kapantzak
kapantzak

Reputation: 11750

You need to use event delegation:

$(document).on('mouseover', '#element_in_wb_page', function() {
    // your function
});

In your case:

$(document).on('mouseover', '#img5', function() {
    $(this).fadeOut(2000);
});

Upvotes: 2

Related Questions