0

Why is this code working on jsfiddle but not my demo web page. It would be greatly appreciated if someone would be able to help me with this problem. Thanks and have a great day. I find it very weird why this is happening. Please help me out.

$('#img1').click(function() {
  $('#aum').html('Text 1');
});

$('#img2').click(function() {
  $('#aum').html('Text 2');
});


$('#img3').click(function() {
  $('#aum').html('Text 3');
});
  
/** --OR-- you could get the images alt attribute and print that out 

$('#aardvark').click(function() {
  var alt = $(this).attr('alt');
  $('div').html(alt);
});
**/
* { margin:0;padding:0; }
body { background:#E9EEF5; }

ul {
  list-style-type:none;
  width:900px;
  margin:10px auto 0;
}

li {
  margin:0 10px;
  display:inline-block;
}

div {
  font:20pt 'Georgia';
  height:50px;
  width:674px;
  margin:20px auto 0;
  text-align:center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<img src="http://tomroof.com/tinymonster/wp-content/uploads/2013/02/pic1.png" id="img1" alt="img1"/>
  <img src="http://tomroof.com/tinymonster/wp-content/uploads/2013/02/pic2.png" id="img2" alt="img2"/>
  <img src="http://tomroof.com/tinymonster/wp-content/uploads/2013/02/pic3.png" id="img3" alt="img3"/>


<div id="aum"></div>

<div>Another Div that shouldn't change</div>
  • Perhaps its in the ordering of the script includes. Seems here you have such followed by image tags. Implies you dont know where to have script includes. – GetSet Aug 29 '20 at 04:12
  • Fiddles automatically wrap your code in a load event handler – charlietfl Aug 29 '20 at 04:13

1 Answers1

0

This happens due to the fact that the page is loaded but the script not

Connect the JQuery script after HTML elements.

or wrap the whole code JQuery.

$(() => {
  // your code
});
Tigran Abrahamyan
  • 756
  • 1
  • 4
  • 7
  • jQuery can be loaded in header. The issue with after loading has to do with page load time. Which I think at this point doesn't matter – GetSet Aug 29 '20 at 04:14
  • That worked. But when i put my search bar code in it the code does not work. please take a look. $('#img4').click(function() { $('#aum').html('
    '); });
    – jessie williams Aug 29 '20 at 04:19
  • @jessiewilliams I just checked it works for me. Maybe it doesn't work for you because you click on an element that is not in the DOM? $('#img4').click(function() { ... } You do not have a picture with id img4 – Tigran Abrahamyan Aug 29 '20 at 04:29
  • It still will not work – jessie williams Aug 29 '20 at 07:14