0

I have a bunch of Paragraphs in a Section. In desktop I want to wrap every 3 paragraphs in a row, in Tablets I want to wrap every 2 paragraphs in a row, and in mobiles no wrap should happen.

I have written the following code and it is working, but the problem is when I change the resolution or switch Desktop to Tablet mode then the condition is not getting applied automatically until I refresh the page.

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.my_theme_name = {
    attach: function (context, settings) {

    if (($(window).outerWidth() >= 768) && ($(window).outerWidth() <= 1199)){
     var divs = $("section > p");
      for(var i = 0; i < divs.length; i+=2) {
        divs.slice(i, i+2).wrapAll("<div class='row'></div>");
     }
    }

    if (window.outerWidth >= 1200) {
     var divs = $("section > p");
      for(var i = 0; i < divs.length; i+=3) {
        divs.slice(i, i+3).wrapAll("<div class='row'></div>");
     }
    }

   }
 };
})(jQuery, Drupal, drupalSettings)

Is there a way, apply jQuery condition automatically on screen size change without page refresh ??

Note: This JS file is using in Drupal site.

Rajesh B
  • 39
  • 4
  • Does this answer your question? [jQuery on window resize](https://stackoverflow.com/questions/9828831/jquery-on-window-resize) – freedomn-m Jul 08 '21 at 09:53
  • 1
    Interesting that you've tagged [tag:media-queries] but not mentioned them in your question. Yes, this would be best suited with an `@media` in your *css* (not using jquery at all). – freedomn-m Jul 08 '21 at 09:54
  • @freedomn-m Thanks for quick reply.. I wanted this to be done with jQuery only, removed the media-queries tag. Also that solution is not working for me. Its working only first if condition – Rajesh B Jul 08 '21 at 10:05
  • To paraphrase your question to *Is there a way [to run some javascript code] automatically on screen size change without page refresh* - the answer is: `$(window).on('resize', function(){ .. your code .. })` I suggest you refactor your code so that it doesn't add `div`s so that it can be run multiple times. eg add/remove the `row` class to an existing div wrapper. – freedomn-m Jul 08 '21 at 10:21

0 Answers0