Search code examples
javascripthtmljqueryiframedarkmode

Change iframe source when dark mode is enabled and change it back when dark mode is disabled


GOAL: I would like to change the source of an iFrame when onclick="toggleDarkMode() is activated and change it back when onclick="toggleDarkMode() is disabled.

PROBLEM: My current "Dark Mode" button only changes the iFrame source once, when onclick="toggleDarkMode() is activated to "//www.twitch.tv/embed/yaydank/chat?parent=icelz.s3.amazonaws.com&darkpopout". Then when I click it again it doesn't change the source back to "//www.twitch.tv/embed/yaydank/chat?parent=icelz.s3.amazonaws.com&popout". If anybody could help me sort this out, I would highly appreciate it. Thank you in advance.

My current default iframe code when the page is loaded:

<iframe id="myFrame" src="//www.twitch.tv/embed/yaydank/chat?parent=icelz.s3.amazonaws.com&popout" frameborder="0" scrolling="no" height="100%" width="100%"></iframe>

My current javascript code, which changes the source of the iframe when onclick="toggleDarkMode() is activated:

<script>
function myFunctionDark() {
    document.getElementById("myFrame").src = "//www.twitch.tv/embed/yaydank/chat?parent=icelz.s3.amazonaws.com&darkpopout";

}
</script>

This is my current "Dark Mode" button, which triggers "toggleDarkMode" and "myFunctionDark" function:

<i class="material-icons dropdown-toggle" onclick="toggleDarkMode();myFunctionDark()" data-tooltip="Dark Mode" data-tooltip-pos="left">wb_sunny</i>

LIVE LINK WHERE THE PROBLEM IS PRESENT ("Dark Mode" button is at the top right corner")


Solution

  • You are always executing myFunctionDark() and it only set the chat dark. Try setting a condition inside like this:

    function myFunctionDark() {
      if($(".app-container").hasClass("dark")) {
        document.getElementById("myFrame").src = "//www.twitch.tv/embed/yaydank/chat?parent=icelz.s3.amazonaws.com&darkpopout";
      } else {
        document.getElementById("myFrame").src = "//www.twitch.tv/embed/yaydank/chat?parent=icelz.s3.amazonaws.com&popout";
      }
    }