0

I'm trying to change the id of a div on mobile vs desktop.

Using

$(document).ready(function() {

  var bodyWidth = $('body').width();

  if (bodyWidth > 320 && bodyWidth < 400) {
    document.getElementById("carousel-example");
    if (div) {
      div.setAttribute("id", "carousel-mobile");
    }
  }

  if (bodyWidth > 768 && bodyWidth < 1024) {
    document.getElementById("carousel-mobile");
    if (div) {
      div.setAttribute("id", "carousel-example");
    }
  }

  if (bodyWidth > 1224) {
    document.getElementById("carousel-mobile");
    if (div) {
      div.setAttribute("id", "carousel-example");
    }
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

And it's not working, can anyone help?

Luis Alves
  • 1,315
  • 1
  • 10
  • 16
  • 1
    `document.getElementById("carousel-example");` is supposed to be `let div = document.getElementById("carousel-example");` (also: you're not dealing with certain widths at all, and changing an element's id is very likely a bad idea and not a good approach to solve your problem) –  Oct 28 '20 at 16:40
  • 1
    you are not assigning the value of `div` anywhere before using it. – daddygames Oct 28 '20 at 16:41
  • I'm not a programmer, just a designer trying to make something work :-) – Luis Alves Oct 28 '20 at 16:48
  • If there is a better way to do this, please advise – Luis Alves Oct 28 '20 at 16:49

1 Answers1

1

Instead of hardcoding widths, you can use different ways that javascript provides to detect the device (What's the best way to detect a 'touch screen' device using JavaScript?)

The issue which you may face if you replace the ID like this:

suppose your javascript is loaded before the HTML rendered, and later you change the Id, then events on that may not work, and you may land up solving that issue. and many more issues may come.

If you don't want to get into these complications, then I would suggest. just before your div is getting rendered(before you add your html code of this carousel), set the ID at that time itself, instead of replacing the ID later.

I mean, first time your html is getting added to DOM, it should have correct ID.

but if you want your code to work, then Chris has answered it in comments, you have not assigning to the variable.

KushalSeth
  • 3,265
  • 1
  • 26
  • 29