Using jQuery to create a click event handler for an image

How can I call a function when clicking an image with jQuery?

This is the HTML code I am working with:

<div id="fixed-navbar">
            <div class="nav-left">
                <img id="back" src="back.png">
            </div>
... (some other code)
</div>

I am trying to write a script to call a function when the above image is clicked:

$("#back").on('click', '.nav-left', function(e) {
                e.preventDefault();
                window.history.back();
});

Why isn't this script working as expected?

PS: These div's are added dynamically

Answer №1

The event binding is set on .nav-left rather than #back itself.

$("#back").on('click', function(e) {
    e.preventDefault();
    window.history.back();
});

If your image is generated dynamically within the div.nav-left element, you just need to switch the selectors around.

$(".nav-left").on('click', '#back', function(e) {
    e.preventDefault();
    window.history.back();
});

If all of your content is dynamic, this is how you should approach it.

$("body").on('click', '#back', function(e) {
    e.preventDefault();
    window.history.back();
});

Rather than using body, you can specify the nearest enclosing parent element that is not added dynamically to the page.

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

In order to retrieve the latitude and longitude of a specific address using arcGis JavaScript, follow these

Hello, I'm wondering how to obtain the Latitude and Longitude using arcgis JavaScript. Can anyone help me with this? ...

Positioning a div above a Bootstrap navbar that disappears when scrolling

I am currently using bootstrap to design a website, and I am attempting to create a div that would initially appear above the navbar on an unscrolled webpage. However, once the user starts scrolling, I want this div to disappear and have the navbar fill it ...

What is causing the variables in my HTML tags to not appear?

I am currently working on a component to display random products from an array. Despite being able to see the attributes like props.products[random].company when I console log them, they are not rendering properly when placed inside HTML tags. Although th ...

Master the art of linking multiple axios calls together in a single promise

I've been delving into Axios and promises lately, trying to grasp the concept. It seems like I'm on the right track, but there are definitely some mistakes in my approach. My javascript method is supposed to return a promise, within which I have ...

I'm currently facing a conflict problem and I'm struggling to identify the root cause

I have integrated a date picker into my form, using the following resources: for the date picker plugin and 1.9.1 jquery.js for jQuery version. However, I encountered an error in this file: TypeError: $.isPlainObject is not a function if ( $.isPlainObje ...

The fixed positioning isn't functioning properly, here is the code snippet from my CSS and HTML

CSS Code I am not associated with any element that has the CSS property overflow: hidden. <div class="header"> <section class="top"> <div class="links"> &l ...

java code unicode feature in csharp

Here's the code I am using: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); The 'title' property contains values en ...

Executing a JavaScript function when an HTML page is loaded within an OBJECT Tag

I have a situation where I am loading an HTML page inside an object tag. Since the iPad does not support iFrames, I decided to use the object tag to load external HTML pages into a container. Everything is working well so far, but now I want to be able t ...

upgrading from Internet Explorer 8 to Internet Explorer 9

Similar Topic: Transitioning from IE8 to IE9 Are there any recommendations for transitioning from IE8 to IE9 in order to operate an application smoothly? What factors should be taken into account for CSS, HTML, and JavaScript prior to the migration? ...

Using JQuery to attach an onclick event to multiple links that share the same class

There are links on the website with the ".tel" class <a class='tel' href="http://example.com">Link</a> To add an onclick event to all these links, follow these steps onclick="return gtag_report_conversion('http:// ...

Anchor tags fail to function properly due to jQuery interference

I am attempting to modify the class of the li tag on a navbar to active when I am on that page. jQuery successfully changes the li class to active, but the <a> inside it stops functioning. When I deactivate the js file, the anchor tags start workin ...

Trouble arises when implementing a nested flex layout in Angular Material shorthand

I'm having trouble identifying the issue with this particular layout. My goal is to maintain a Single Page Application layout where the "deepest" component only becomes scrollable if the viewport height is too small, as indicated in the snippet by us ...

Transfer the html div element to the ajax request

My server-side code runs multiple bigquery queries and organizes the results in a table. The client calls this code via an ajax request. I want to send the table/div generated by the server-side code to the client so that it can be rendered there. Is this ...

Seeking guidance on implementing toggle buttons for navigation bar items on mobile screens, enabling them to toggle for a dropdown menu. The tools at my disposal are HTML, CSS

I want to make the navigation menu responsive by adding a toggle button for the dropdown menu on mobile screens. Here is the code snippet: .nav-link { display: inline-block; position: relative; color: black; } html,body{ height: 100%; width ...

Retrieving the value of a local object property by using a string identifier

How can I retrieve the value of a property from a local object variable using its fully qualified variable name? function foo() { var obj = { prop: "val" } var valueStr = "obj.prop"; var value = // code here that gets value using ...

What is the best method to shift the middle div to the top of the CSS layout?

My goal is to create a responsive web page with three divs arranged in one column for small screens and two columns for larger ones. However, the layout doesn't look quite right unless the middle div is moved to the top like this: https://i.sstatic.n ...

Scrolling without limits - cylindrical webpage (CSS/JS)

Is it possible to create a page that infinitely scrolls from top to top without going straight back to the top, but instead showing the bottom content below after reaching it? Imagine being able to scroll up and see the bottom above the top like a 3D cylin ...

Is the positioning of 'clear:both' influenced by external floated elements?

I have 2 divs. One is styled with float:left and has a width of 100px, making it red. The other div is green and has a margin-left:101px, but is not floated. Within the green div, I inserted another div with two floated elements: The outcome is as follo ...

Error: Unable to access attributes of null object (specifically 'disable click')

Currently, I am integrating react-leaflet with nextjs. Within the markers, there are popups containing buttons that open another page upon click. However, I have encountered an error when navigating to the new page: Unhandled Runtime Error TypeError: Canno ...

Ways to trigger the upgradeneeded event in IndexedDB without upgrading the version

Can you help me understand the "upgradeneeded" event? I want to be able to check the database every time a user reloads the page. Is there a way to trigger this without actually upgrading the version of the indexedDB? request.addEventListener('upgrad ...