0

Onclick function not working in this case:

HTML

<img src="http://www.simplypo.ayz.pl/wp-content/uploads/2017/07/krakow-
3.png" id="gabi" style="text-align: justify;" onClick="myFunction()" />

<p id="demo">Hi!</p>

JS

function myFunction() {
var str = document.getElementById("demo").innerHTML; 
var res = str.replace("Hi", "Hello");
document.getElementById("demo").innerHTML = res;
}

https://jsfiddle.net/kkdrrmhd/2/

gainsky
  • 177
  • 10
  • 1
    It's because you've attached the code on the `onLoad` function, click on the cog in the javascript panel to see what I mean [Example](https://jsfiddle.net/GMan134/d66j01jn/). Either add it to the head/body or do `window.myFunction = function etc` – George Jul 18 '17 at 13:03

3 Answers3

1

try this

<img src="http://www.simplypo.ayz.pl/wp-content/uploads/2017/07/krakow-3.png" id="gabi" style="text-align: justify;" onClick="myFunction('<h2>Gabriela</h2> tomatoes.121')" />
<div id="text-display">dsadasd
</div>
<p id="demo">Visit Microsoft!</p>

<script>
function myFunction(sample) {
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace("Microsoft", "W3Schools");
    document.getElementById("demo").innerHTML = res;
}
</script>

Fiddle here

suraj mahajan
  • 832
  • 1
  • 12
  • 21
1

It's because your code is wrapped in a window.onload function by default in JSFiddle. To change that, click the JavaScript settings icon and change it to one of the "No wrap" options

enter image description here

James Long
  • 4,629
  • 1
  • 20
  • 30
1

I recommend using addEventListener instead of inline event listeners:

function replaceContents () {
  var str = document.getElementById("demo").innerHTML; 
  var res = str.replace("Hi", "Hello");
  document.getElementById("demo").innerHTML = res;
}

document.getElementById('gabi').addEventListener('click', replaceContents);
<img src="http://www.simplypo.ayz.pl/wp-content/uploads/2017/07/krakow-3.png" id="gabi" style="text-align: justify;" />

<p id="demo">Hi!</p>
PeterMader
  • 6,987
  • 1
  • 21
  • 31