2

I'm trying to render one div before another.

I've tested the js on my local machine to make sure it works by creating a simple page. The code is as follows:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
    <div id="QWERTY">
        <div class="content">   
            <div class="field-name-field-image-one">IMAGE</div>
            <div class="body">BODY</div>
        </div>
    </div>       
<script>$('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples</script>

</body>
</html>

I've added the following code to a js file on my Drupal site:

(function ($, Drupal, window, document, undefined) {

    $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples

})(jQuery, Drupal, this, this.document);

My .info file links to the js and it is loading. Other elements that require javascript are working too. I've even tried adding the script in the html.tpl file, but that did not work either.

The divs I am trying to affect are nested deep within the html markup, and have several classes applied to them, compared to the simple version I have made. Could that be the reason? Am I not being specific enough?

0

It's most likely because you're attaching the event before the DOM is fully loaded (so the element you're trying to attach to doesn't exist yet). In your example HTML the JS is included after the DOM is loaded which is why it works.

Try this:

(function ($, Drupal, window, document, undefined) {
  $(function() {
    $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples
  });

})(jQuery, Drupal, this, this.document);
2

This will help you

(function ($) {


Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
  $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples

}


};
})(jQuery);

Read this https://drupal.org/node/756722 It will definitely help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.