How to bind click event on image added using CSS 'background-image' property in jQuery


Tags: javascript,jquery,css,css3

Problem :

Here is my fiddle link

I guess my question is clear by title itself. Still, what I am looking for is an way to bind click event on the image added using css's background-image property.

I know, I could have achieved the similar functionality (of placing image over input field using this way or this way) by simply positioning <img> tag over input box and then handling the required events but that way didn't seem too flexible with input fields of varying width and height or if the wrapping div doesn't have position:relative; as its property.

If adding event on image loaded with background-image is not possible then how to make the later approach more flexible.

Hope I have conveyed my issues clearly.

Thanks.



Solution :

Something like this appears to also work:

$('.cross').click(function(e) {
  var mousePosInElement = e.pageX - $(this).position().left;
  if (mousePosInElement > $(this).width()) {
     $(this).val(''); 
  }
});

Link to example


    CSS Howto..

    How to make chrome respect tables with fixed column width

    How can I make a DIV element Fixed but non-Scaleable?

    How to visually indicate current page in ASP.NET MVC?

    How to do something like border-top-left-color. [CSS]

    How to isolate CSS rules inside a div?

    How hard is it to make an expanding tab in CSS?

    CSS How to make DIV Border Dynamic in Width

    how to css for data attribute [duplicate]

    How to create triple div border in CSS

    How to create DropDown MenuBar using CSS

    How do I set the table row heights to minimum except last row?

    how to zoom in an image and center it

    How to create a horizontal calendar with nested lists?

    How to put a canvas on an image?

    How to show CSS transitions only on hover?

    How to Detect css by iPhone/iPad

    How to make width of nested CSS elements all the same?

    How to implement two sets of CSS Tabs on one page?

    How to configure css flexbox so height of one of the block depends on it content?

    How to set date search toolbar field width on autoresize

    How would I get my horizontal navigation bar to span the full width?

    How to select “label for=list[]” in CSS?

    How to make a CSS button work correctly?

    How to detect css properties in div

    How to get 60 fps in css element width animation?

    css image not showing up

    How do I override the default way Wordpress' determines the .current-menu-item class?

    How to change css position left to right using jquery?

    How to center inside divs in a 1140px fluid responsive framework?

    How do I insert an image in HTML so that its fills up the entire screen regardless of screen size?