JavaScript code is not updating the image source despite the presence of an if statement

Can someone help me figure out where I've gone wrong? I have a code snippet here that's meant to toggle between two images on click, but nothing happens when I click the image. An alert in the click function is triggered successfully, but not within the if statement. What did I mess up?

HTML:

<html>
<head>
<link href="../CSS/209.css" rel="stylesheet" type="text/css">
</head>

<body>

 <div id="trim">green209green209green209</div>

 <h1 align="right">about House Felice</h1>

<center>

 <img src="../Images/fakevid.png" width="70%" height="48%"><img src="../Images/videonav1.png" width="25%" height="48%">


<div id="wrapper">

<div id="kitchen" align="left"> 
    <img id="pricetile1" src="../Images/kitchen.png">
    <img id="pricetile2" src="../Images/french.png" data-price="100" />
    <img id="pricetile3" src="../Images/german.png" data-price="200" />
</div>

<div id="floor" align="left">
    <img id="pricetile1" src="../Images/floors.png">
    <img id="pricetile4" src="../Images/mixed.png" data-price="300">
    <img id="pricetile5" src="../Images/allwood.png" data-price="400">
</div>

<div id="energy" align="left">
    <img id="pricetile1" src="../Images/energy.png">
    <img id="pricetile6" src="../Images/green.png" data-price="500">
    <img id="pricetile7" src="../Images/standard.png" data-price="600">
</div>
</div>



<div id="price"><p>total: $<span id="total">0.00</span><p></div>
<div id="next"> <p>next house</p></div>

JAVASCRIPT:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
 <script type="text/javascript" src="js/script.js"></script>


 <script>


             $('#pricetile2').click(function(){

    console.log(document.getElementById("pricetile2").src);
    if (document.getElementById("pricetile2").getAttribute('src') == "../Images/french.png" )
    {
        document.getElementById("pricetile2").getAttribute('src') = "../Images/french2.png";
        console.log(1);
    }
    else 
    {
        document.getElementById("pricetile2").getAttribute('src') = "../Images/french.png";
        console.log(2);
    }   
 });

 var container = document.getElementById('wrapper');
 var lines = container.children;
 var numLines = lines.length;
 document.addEventListener('click', function(e) {
    if (e.target.tagName == 'IMG' && container.contains(e.target)) {
var selected = e.target.parentNode.getElementsByClassName('selected');
if (selected.length)
  selected[0].className = selected[0].className.replace('selected', '');
e.target.className = 'selected';
var total = 0;
for (var i = 0; i < numLines; i++) {
  var selected = lines[i].getElementsByClassName('selected');
  if (selected.length)
    total = total + Number(selected[0].dataset.price);
}
document.getElementById('total').innerHTML = Number(total).toFixed(2);
}
}, false);


 document.getElementById("calc").innerHTML = x;

</script>

Answer №1

console.log(document.getElementById("pricetile2").src);

This code snippet displays the full URL of an image, rather than just the relative path. For example, instead of showing "../Images/french.png," it will show http://fiddle.jshell.net/Images/french.png. You can see an example at http://jsfiddle.net/klickagent/wr01jxmb/.

Therefore, it's important to check the full URL of the image in the if statement.

As Barmar suggested, you can use:

document.getElementById('pricetile2').getAttribute('src');

This will give you the exact value in the src tag (the relative path).

Answer №2

A simple modification needed for this code to function properly is as follows:

if (document.getElementById("pricetile2").src.indexOf("Images/french.png") >= 0)

instead of

if (document.getElementById("pricetile2").src == "../Images/french.png")

or alternatively,

if (document.getElementById("pricetile2").getAttribute("src") == "../Images/french.png")

This adjustment is necessary because comparing relative URLs directly, as attempted initially, won't work. (Acknowledgment to Barmar for suggestion number two)

Answer №3

If you are utilizing jQuery, my suggestion is to incorporate jQuery in defining your src as well. One way to achieve this is by using jQuery's .attr() function like so:

$('#pricetile2').click(function(){

    if ( $("#pricetile2").attr('src') == "../Images/french.png" ) 
    {
        $("#pricetile2").attr('src','../Images/french2.png');
    }
    else 
    {
        $("#pricetile2").attr('src','../Images/french.png');
    }   
});

The issue with your current method is that

document.getElementById("pricetile2").src
will provide the absolute path instead of the relative path (e.g., it may return something like
http://example.com/Images/french.png
).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Inserting Text with Line Breaks into a Textarea Using jQuery and PHP MySQL

I am dealing with a form that users complete with a textarea input. This form is saved into a MySQL database, and later the user has the ability to make edits. The problem I am facing is that whenever I try to use AJAX to provide suggestions for the textar ...

Mocha throwing 400 bad request error when making a post request with raw data

var expect=require('chai').expect; var http=require("http"); var request = require('request'); var env = require('./environment'); describe("Testing Callflow Functionality", function(done) { //this.timeout(15000); it("Tes ...

Ways to verify the existence of empty arrays in an Object using underscore.js or jQuery

Is there a more efficient method to determine whether an object contains empty arrays (0-*) aside from the following approach: emptyArr: function() { var obj = getObj(); return obj.abc.length == 0 || obj.def.length == 0 || obj.ghi.length = ...

Fade image and background using Jquery on click event

I've been browsing various sources and utilizing different techniques I've come across (primarily on this platform) to guide me in my progress so far. However, I fear that I may have unintentionally backed myself into a corner by choosing an inco ...

Adjust the svg rate using jQuery or JavaScript

Seeking help with a gauge I found on CodePen - struggling to adjust bubble values... <path id="Fill-13" fill="#F8B50F" d="M3.7 88.532h26.535v-#.795H3.7z"/> Can change the bars in JS, but not the bubbles using jq/js. Adjust the gauge with values be ...

Interact with various contenteditable sections by navigating with the arrow keys

I have a challenge with multiple <p contenteditable="true"></p> elements on my page. I am seeking a solution to enable the use of arrow keys to navigate seamlessly across these separate elements as if they were one cohesive editable element. F ...

What are some effective techniques to optimize this node.js code and eliminate redundancy?

I am currently in the process of setting up a basic template for my demonstration project and writing my first node.js program. The piece of code below is functioning properly for my initial test, but it contains duplicated sections - Getting connection, E ...

Is there a way to use JavaScript to switch the entire div on and off

I have a function called done that I want to use to toggle the visibility of my "temp" division. tasks.innerHTML += `<div id="temp"> <span id="taskname"> ${input.value} </span> <button class="d ...

How to change from using position: sticky to fixed after scrolling to a specific div

Is there a way to transition the position of sticky content from sticky to Fixed while scrolling down and moving to the next rows, keeping it fixed until just before the footer, where it should scroll again? For example, <!DOCTYPE html> <html ...

JavaScript is having trouble retrieving URL variables when there are multiple values in the query string

Currently, I am leveraging a JavaScript function to extract URL values and pass them to jQuery using the following method: function grabUrlValues() { var values = [], hash; var params = window.location.href.slice(window.location.href. ...

The raycaster in Three.js seems to be having trouble selecting the correct object

Hey everyone, I'm currently working on selecting objects using a raycaster and I want to change the material of the first selected object. Everything works smoothly until I pick the object - when I select the first element, only one object changes. I ...

Finding Your Way with a Quick Navigation Bar

I am facing a simple issue, but due to my lack of experience in design, I find it challenging. Currently, I am working on a basic PHP website project. I have a navigation bar and want the content of a specific panel to change when a navigation button is c ...

What is the process for calculating and determining the exact area the div should be released?

I am currently developing a drag-and-drop application using only Javascript. I have successfully implemented the dragging functionality, allowing elements to be moved randomly within the page. However, I now face the challenge of creating a drop zone with ...

How come I am getting only a single outcome when iterating through a dataset array?

I have a fetch API that returns an array of objects, and within those objects are nested arrays and other objects. My goal is to filter out only the objects that contain a specific value. Specifically, I want to retrieve objects with an id of 11 from the p ...

Exploring Nashorn's Global Object Variables Through Access and Intercept Techniques

I recently came across a question called "Capturing Nashorn's Global Variables" that got me thinking. I'm facing limitations when it comes to capturing the assignment of variables to the global object. For example, let's say I evaluate the ...

Guide to creating a cryptosystem using a Synchronous Stream Cipher with Vue js

I am currently working with a pseudo-random number generator that creates binary numbers using a user-supplied polynomial and the LFSR method. To enhance the process, I need to convert a loaded file into binary format so that I can apply the XOR operatio ...

Using Ionic's ngmodel directive with a list and associating ids as keys

Having an issue. Trying to connect a toggle button with a list and use the toggle's id as a key. //Function for conversion transform(d) { alert(d); //when i put this.id here i have undefined value return Number(d); } <ion ...

Using jQuery to add a class and define a variable when clicked on

In order to achieve the functionality of changing the class of a link to active while removing the active class from other links, and setting a variable value based on the clicked link, you can refer to the code below. When "1" is clicked, the variable fir ...

Carousel featuring multiple items with uniformly sized cards

Anticipated outcome: Consistent height across all cards (each card should adjust its height to match the tallest card) Actual result: Height varies based on text length Code Snippet: NOTICE DIFFERENCES IN HEIGHT AMONG SLIDES ...

How can I use Javascript / D3 to create a color scale mapping 5 hex colors to 17 colors?

If I start with the array of hexadecimal colors ['#1147FF', '#86D8FF', '#FFEF67', '#FF7D11', '#F30000'] in JavaScript, I can achieve the color scale I desire by adjusting the steps on the scales website fro ...