BahaS
BahaS

Reputation: 7

shows same id in different buttons. conflict

i'm loading content of from external html files. page1.html and page2.html. everything is the same except pictures and text. but there is conflict with close button. it closes just page1.html here is example of my code

function close_box() {
    dividid = $(this).parents('div').attr('id');
    divid = $('#' + dividid).parents('div').attr('id');
    dividofid = $('#' + divid).parents('div').attr('id');
    alert(dividofid);
    return false;
}

and this is html

<div id="page1id">
    <div id="danis">
        <div id="close_box"> <a onclick='close_box.call(this);'>page1 close</a> 
        </div>
    </div>
</div>
<div id="page2id">
    <div id="danik">
        <div id="close_box"> <a onclick='close_box.call(this);'>page2 close</a> 
        </div>
    </div>
</div>


http://jsfiddle.net/LULrE/3/

Upvotes: 0

Views: 162

Answers (2)

Steve
Steve

Reputation: 8640

Your ids on a page need to be unique. If you need multiple ids on the page with the same value on the same page for CSS reasons, use the class attribute.

For JS purposes, if you look for a specific id on the page, only the first one is being returned. In your case $('#' + dividid); resolves to $('#close_box'); which returns only the first element it finds.

I would approach your problem like this:

HTML:

<div id="page1id" class="closeable">
    <div id="danis">
        <div id="close_box"> <a onclick='close_box.call(this);'>page1 close</a> 
        </div>
    </div>
</div>
<div id="page2id" class="closeable">
    <div id="danik">
        <div id="close_box"> <a onclick='close_box.call(this);'>page2 close</a> 
        </div>
    </div>
</div>

JS:

function close_box() {
    var page_level_div = $(this).closest('.closeable');
    page_level_div.hide()
    return false;
}

EDIT:

Last but not least, I would suggest you NOT use onclick handlers in your HTML. Especially since you are already using jQuery, you could easily rewrite your code like this:

HTML:

<div id="page1id" class="closeable">
    <div id="danis">
        <div class="close_box"> <a href="">page1 close</a> 
        </div>
    </div>
</div>
<div id="page2id" class="closeable">
    <div id="danik">
        <div class="close_box"> <a href="">page2 close</a> 
        </div>
    </div>
</div>

JS:

$(document).ready(function() {
    $(".close_box").click(function() {
        $(this).closest('.closeable').hide();
    });
});

Upvotes: 3

Ayush
Ayush

Reputation: 42450

Here is your corrected code:

function close_box() {
    var divid = $(this).parent().parent().parent().attr('id');
    alert(divid);
    return false;
}

The problem with your code was that dividid gets close_box, but then when you use that id in a selector, it picks the first div with an id of close_box, which is the div that corresponds to page1.

Fiddle

Upvotes: 0

Related Questions