Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Changing the CSS on an element loaded with ajax?

I need to change the position of an element i'm loading with ajax. I want to use .css() to change it but jQuery can't find the element cause it's not being recognized. How do i do to make jQuery "recognize" the element?

I've read about live() and delegate() but i can't get neither one of them to work as i want them to. I'd really appreciate some help!

like image 536
qwerty Avatar asked Jul 28 '11 21:07

qwerty


People also ask

Can jQuery manipulate CSS?

The jQuery CSS methods allow you to manipulate CSS class or style properties of DOM elements. Use the selector to get the reference of an element(s) and then call jQuery css methods to edit it. Important DOM manipulation methods: css(), addClass(), hasClass(), removeClass(), toggleClass() etc.

How do you trigger a change event after AJAX call?

ajax({ url, data: data, type: "POST", dataType: "json", success: function(cbdata) { update_table(cbdata); } }); } $('#selector'). on('click', changeDate); So you can call changeData() when you need it.

Does AJAX use CSS?

AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script. Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display.

Can jQuery and AJAX be used together?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!


2 Answers

Make the css change in the complete or success function of the ajax call. Assuming you're using load:

$('#el').load(
    url,
    data,
    function(){
        $('#selector').css('position', 'absolute');
    }
);

Alternatively (and easier to give as an example) register an ajaxComplete event

$(document).ajaxComplete(function(){
    if($('#elementID').length != 0) {
        $('#elementID').css('position', 'absolute');
    }
});

This is fired each time an ajax request completes, checks to see if #elementID exists and if so applies the css.

like image 60
Adam Hopkinson Avatar answered Nov 15 '22 22:11

Adam Hopkinson


If you have to markup in a js variable then you can do it as below.

$(markup).find("requiredElement").css({ set the properties here });
like image 20
ShankarSangoli Avatar answered Nov 15 '22 22:11

ShankarSangoli