0

i have a function that creates an album and with jquery's post function and then it create the necessary HTML elements and append them to the document. the problem is that the elements are a link and its target, while the link woks fine when i refresh the page it seems like the browser couldn't found the added target which was created with jquery. how could i target an element with javascript that was created with either jquery or javascript. thanx in advance. EDIT:

the jsfiddle code

code:

btn        = document.getElementById('add_album_btn');
btn.addEventListener('click', add_album_btn_func, false);
function add_album_btn_func(){
    div              = $('<div>').addClass('albums_div');
    a                = $('<a>').addClass('albums');
    a.attr('onclick', 'return false;');
    a.attr('onmousedown', 'autoScrollTo("new_section");').attr('href', '#');
    a.append('&#9733; New Album');
    div.append(a);
    section          = $('<section>').attr('id', 'new_section');
    header           = $('<header>').addClass('inner_header');
    header.append($('<h4>').append('New Album'));
    inner_section    = $('<section>').append($('<h5>').append('Images List :'));
    footer           = $('<footer>').addClass('inner_footer');
    upload_btn       = $('<a>').attr('id', 'new_section').addClass('upload_file ajax');
    upload_btn.attr('href', 'some/link/');
    upload_btn.append('Upload a file');
    footer.append(upload_btn);
    section.append(header);
    header.after(inner_section);
    inner_section.after(footer);
    $('#wrap').append(div);
    $('#separator').after(section);
}
var scrollY          = 0;
var distance         = 40;
var speed            = 24;
function autoScrollTo(el){
    var currentY     = window.pageYOffset;
    var targetY      = document.getElementById(el).offsetTop;
    var bodyHeight   = document.body.offsetHeight;
    var yPos         = currentY + window.innerHeight;
    var animator     = setTimeout('autoScrollTo(\'' + el + '\')', speed);
    if(yPos >= bodyHeight){
        clearTimeout(animator);
    }else{
        if(currentY < targetY - distance){
            scrollY = currentY + distance;
            window.scroll(0, scrollY);
        }else{
            clearTimeout(animator);
        }
    }
}​

EDIT: apparently i wasn't clear enough what i want is the following: i have this javascript code:

$(document).ready(function(){
    $('.lightbox').click(function(){
        $('.backdrop').animate({'opacity': '.50'}, 300, 'linear');
        $('.box').animate({'opacity': '1.00'}, 300, 'linear');
        $('.backdrop, .box').css('display', 'block');
    });
    $('.close').click(function(){
        close_box();
    });
    $(".backdrop").click(function(){
        close_box();
    });
    function close_box(){
        $('.backdrop, .box').animate({'opacity': '.0'}, 300, 'linear', function(){
            $('.backdrop, .box').css('display', 'none');
        });
    }
    a = $('<a>').addClass('lightbox').attr('href', '#').append('<br>Click to Test.');
    $('body').append(a);
});

the html:

<h1>jquery light-box</h1>
<a href=# class=lightbox>open lightbox</a>
<div class="backdrop"></div>
<div class="box"><div class="close">X</div>this is the light box</div>

the CSS:

body{
    font-family: Helvetica, Arial;
}
.backdrop{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #000000;
    opacity: .0;
    z-index: 50;
    display: none;
}
.box{
    position: absolute;
    top: 20%;
    left: 30%;
    width: 500px;
    height: 300px;
    background: #ffffff;
    z-index: 51;
    padding: 10px;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    -khtml-border-radius: 10px;
    border-radius: 10px;
    box-shadow: 0 0 5px #444444;
    display: none;
}
.close{
    float: right;
    margin-right: 6px;
    cursor: pointer;
}

the jsfiddle link

the problem when the second link is added with javascript it seems to be llike its invisible to the function. any help thanx in advance.

NOTE: this lightbox code is from the PHPacademy tutorials.

NOTE: if you'r going to give the answer about re_writing the function and re-assign it to the new created element i already know that i need another way.

thanx in advance.

6
  • 3
    Post some code to illustrate the problem you're having. Commented Dec 5, 2012 at 7:38
  • 3
    If you append an element with jQuery to the DOM and make no server call in order to save this, if you refresh the page, it is normal that you have no new element... Commented Dec 5, 2012 at 7:39
  • In a general sense you can definitely add links that target another element on the page dynamically: jsfiddle.net/AMJJP - Are you saying your case you refresh the page after adding the elements? Commented Dec 5, 2012 at 7:43
  • no, that's not what i meant the function make a post request with jquery to the server and then i get the returned data and use jquery to create a link and its target an append the both to the DOM, the problem is when i click the link it wont take me to the target (NOTE: it a local link), but when i refresh the page everything works fine. so the problem is in the jquery generated target the browser can't find it. Commented Dec 5, 2012 at 7:45
  • 1
    Please show your code, and if possible set up a jsfiddle demo. You can see in the demo I provided in my previous comment that dynamically added elements can function as href=#idOfElementAddedDynamically" links and target elements... Commented Dec 5, 2012 at 7:47

3 Answers 3

1

Try this:

$(".lightbox").live("click", function() {
        $('.backdrop').animate({
            'opacity': '.50'
        }, 300, 'linear');
        $('.box').animate({
            'opacity': '1.00'
        }, 300, 'linear');
        $('.backdrop, .box').css('display', 'block');
    });

DEMO HERE

UPDATE

Since the lightbox class element is added dynamically, you need to use event delegation to register the event handler like:-

// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document.body).on('click', '.lightbox', function (e) {
    e.preventDefault();
    $('.backdrop').animate({
        'opacity': '.50'
    }, 300, 'linear');
    $('.box').animate({
        'opacity': '1.00'
    }, 300, 'linear');
    $('.backdrop, .box').css('display', 'block');
});

DEMO HERE

Sign up to request clarification or add additional context in comments.

6 Comments

live is long deprecated no longer in jQuery. Did you mean to use on?
@JanDvorak yes, you are absolutely right. I have updated the code and the fiddle demo!
Slight improvement: $("body") should be $(document.body)
@JanDvorak I'm curious. Is there any difference between two? Could you please provide some documentation related to it? That would help my learning process. Thanks anyways :)
$('body') is translated by jQuery to document.querySelectorAll("body"). This requires a CSS selector to be parsed by the browser (resulting in unneccessary overhead), then a node-set is looked up based on the selector (which, again is not that fast), wrapped in a NodeSet (allocation costs), which is then unwrapped by jQuery and discarded. $(document.body) performs a property lookup (trivial cost, even if it's actually a getter) and wraps the single element in a jQuery object (which we need anyways).
|
0

As far as I understand, you want to trigger the same lightbox animation when you click on "Click to Test." as when you click on "open lightbox"?

In that case, the .click() just bind the event handler to the CURRENT set of matched elements. What you are looking for is .on() or .delegate()

Fiddle

4 Comments

@Palash both your answers seems to be working but what if it's not about an event like click because my code is not like the example its not binding a function to the click event it's binding a jquery plugin to an element whenever that element is clicked the lighbox is opened the plugin is called colorbox and its called like this: $('.lightbox').colorbox();
Call .colorbox() on the created element when you insert it should work. i.e. change $('body').append(a); to a.appendTo('body').colorbox()
that actually didn't work this did: a.click(function(e){ $.colorbox({href: href}); e.preventDefault(); });
hi how about getting the value of that added item like in a select tag with javascript to perform a post through jquery.
0

How about to target element in callback function of jQuery post? In this callback function, append element to document first, then target it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.