Search code examples
javascriptsharepointsharepoint-designer

Why Sharepoint refresh it self after a javascript function was executed?


I've created a Button in a Content Editor, which changes for example the background color of the content box.

After i press the button, the background color is changed from black to white. But Sharepoint refresh it self automatically and didnt save the change. Does anyone have an idea about this ? It happens in IE and Chrome as well.

Best Regards,

Andy

<button onclick="changeCo()">Change Color</button> 
  <style>
    #contentBox {
    background-Color:black;
    }
    </style><script>
    function changeCo(){
        var elem = document.getElementById("contentBox");
        var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("background-color");
        if (theCSSprop == 'rgb(0, 0, 0)') {
        document.getElementById('contentBox').style.backgroundColor = 'white';
        }else{
        document.getElementById('contentBox').style.backgroundColor = 'black';
        }
    }
    </script>

Solution

  • Just add type='button' to your button element. This should prevent the page reload.

    <button type='button' onclick="changeCo()">Change Color</button> 
    

    But One more thing as @Scott Marcus suggested, if you want to persist the changes even after page refresh/reload then you will have to store these changes to the server/cookies/localStorage.