Make mouse cursor custom image change onclick - javascript

First, I am building a website on cargo. There's html editor but I don't think it works that well along with the site builder itself.
I want my custom image mouse cursor image change while it's on click. I've got three problems here:
I can't set my default cursor to image. (It was successful in cargo but I don't know how to do this on html editor.)
I am not sure how to change my cursor to other image.
I want this to make it happen on my whole site not just on single text or image.

Here you go!
It's quite simple to do:
Just write the cursor property to whatever Selector you want, for the whole WebSite html {...} of course.
html {
background-color: lightgray;
cursor: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/happy.png"), auto;
}
<html>
</html>
There are also a lot of default cursors:
You can check them out here: https://codepen.io/chriscoyier/pen/uCwfB

I would simply use a combination of CSS and JavaScript.
CSS class declaring the appropriate cursor definition with a keyword fallback. Then add a simple onmousedown event to fire the addition of a second CSS class that declares an overriding cursor definition. Add a second onmouseout event to remove the second class that was added on click.
/* keyword fallback example: use pointer, if hand.png doesn't exist */
.cursor-hand {
cursor: url(hand.png), pointer;
}

Related

How to find a function that triggers every second?

http://nylbcsbc.org/t.html
Using dev tools, I was trying to modify a tag's property, as shown in the picture below:
I was trying to remove the whole style attribute of the video tag, but whenever I remove it, it will come back.
I guess this is due to some javascript function that is being executed repeatedly. My question is, how do I find this function and turn it off, so that I can modify the attributes as I do in other normal pages?
To find the function that changes element's attribute:
Assuming you are using google-chrome: right click on the node in Elements panel, in the opened context menu select Break on... -> Attribute Modification; When it breaks, use call stack window to find the cause.
UPDATE:
If you can't control the code, like in your case with jwplayer, instead of trying to remove style attribute, try to override each CSS rule defined there with his initial value:
<style type="text/css">
video {
-webkit-transform: initial!important;
transform: initial!important;
width: initial!important;
height: initial!important;
}
</style>

jQuery to update actual CSS

First off: I'm aware of the jQuery.css() function, but it doesn't work in my case. I'll explain why.
I have a jQuery color picker being used to change the highlighting of a website. I want to apply that color picker to the border of an element which only shows on hover.
The jQuery.css() function only applies the CSS to elements it finds, and does not work on the :hover CSS attribute.
I've tried adding a CSS class which I toggle on the hover, but it comes back to the same problem: I'm trying to change ONLY the hover value.
There's got to be a way to do this, but I've been searching StackOverflow and Google for the better part of an hour now, so I'm invoking xkcd #627
Use the hover event to achieve the same results.
$('selector').hover( function(){
//A function to execute when the mouse pointer enters the element.
$(this).css('property','value');
}, function(){
//A function to execute when the mouse pointer leaves the element.
$(this).css('property','value');
});
I'm adding this as an alternative answer.
If you need to dynamically change your CSS then there is something wrong with your CSS. It's very strange that you need a definition, that you can't toggle with a class and has to be generated dynamically.
Let's say you have a widget that can be in two modes: inactive or active. When it's active elements in it should respond visually to a hover event, when it's not, they shouldn't.
<div id="my-widget" class="my-widget-container">
<div class="element">Something to look at</div>
</div>
CSS
.my-widget-container .element { background-color: #ffffff; }
.my-widget-container.active .element:hover { background-color: #00ff00; }
You switch the mode by:
$("#my-widget").addClass("active");
This will activate the :hover line for the element which now appears interactive.
If I knew more about your situation I could perhaps fix a fitting solution.
Also, jQuery.css is poorly named, perhaps jQuery.style would be a better name since that is exactly what it does.

Apply gradient over page without hindering user interaction [duplicate]

I have a div that has background:transparent, along with border. Underneath this div, I have more elements.
Currently, I'm able to click the underlying elements when I click outside of the overlay div. However, I'm unable to click the underlying elements when clicking directly on the overlay div.
I want to be able to click through this div so that I can click on the underlying elements.
Yes, you CAN do this.
Using pointer-events: none along with CSS conditional statements for IE11 (does not work in IE10 or below), you can get a cross browser compatible solution for this problem.
Using AlphaImageLoader, you can even put transparent .PNG/.GIFs in the overlay div and have clicks flow through to elements underneath.
CSS:
pointer-events: none;
background: url('your_transparent.png');
IE11 conditional:
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='your_transparent.png', sizingMethod='scale');
background: none !important;
Here is a basic example page with all the code.
Yes, you CAN force overlapping layers to pass through (ignore) click events.
PLUS you CAN have specific children excluded from this behavior...
You can do this, using pointer-events
pointer-events influences the reaction to click-, tap-, scroll- und hover events.
In a layer that should ignore / pass-through mentioned events you set
pointer-events: none;
Children of that unresponsive layer that need to react mouse / tap events again need:
pointer-events: auto;
That second part is very helpful if you work with multiple overlapping div layers (probably some parents being transparent), where you need to be able to click on child elements and only that child elements.
Example usage:
.parent {
pointer-events:none;
}
.child {
pointer-events:auto;
}
<div class="parent">
I'm unresponsive
I'm clickable again, wohoo !
</div>
Allowing the user to click through a div to the underlying element depends on the browser. All modern browsers, including Firefox, Chrome, Safari, and Opera, understand pointer-events:none.
For IE, it depends on the background. If the background is transparent, clickthrough works without you needing to do anything. On the other hand, for something like background:white; opacity:0; filter:Alpha(opacity=0);, IE needs manual event forwarding.
See a JSFiddle test and CanIUse pointer events.
I'm adding this answer because I didn’t see it here in full. I was able to do this using elementFromPoint. So basically:
attach a click to the div you want to be clicked through
hide it
determine what element the pointer is on
fire the click on the element there.
var range-selector= $("")
.css("position", "absolute").addClass("range-selector")
.appendTo("")
.click(function(e) {
_range-selector.hide();
$(document.elementFromPoint(e.clientX,e.clientY)).trigger("click");
});
In my case the overlaying div is absolutely positioned—I am not sure if this makes a difference. This works on IE8/9, Safari Chrome and Firefox at least.
Hide overlaying the element
Determine cursor coordinates
Get element on those coordinates
Trigger click on element
Show overlaying element again
$('#elementontop').click(e => {
$('#elementontop').hide();
$(document.elementFromPoint(e.clientX, e.clientY)).trigger("click");
$('#elementontop').show();
});
I needed to do this and decided to take this route:
$('.overlay').click(function(e){
var left = $(window).scrollLeft();
var top = $(window).scrollTop();
//hide the overlay for now so the document can find the underlying elements
$(this).css('display','none');
//use the current scroll position to deduct from the click position
$(document.elementFromPoint(e.pageX-left, e.pageY-top)).click();
//show the overlay again
$(this).css('display','block');
});
I currently work with canvas speech balloons. But because the balloon with the pointer is wrapped in a div, some links under it aren't click able anymore. I cant use extjs in this case.
See basic example for my speech balloon tutorial requires HTML5
So I decided to collect all link coordinates from inside the balloons in an array.
var clickarray=[];
function getcoo(thatdiv){
thatdiv.find(".link").each(function(){
var offset=$(this).offset();
clickarray.unshift([(offset.left),
(offset.top),
(offset.left+$(this).width()),
(offset.top+$(this).height()),
($(this).attr('name')),
1]);
});
}
I call this function on each (new) balloon. It grabs the coordinates of the left/top and right/down corners of a link.class - additionally the name attribute for what to do if someone clicks in that coordinates and I loved to set a 1 which means that it wasn't clicked jet. And unshift this array to the clickarray. You could use push too.
To work with that array:
$("body").click(function(event){
event.preventDefault();//if it is a a-tag
var x=event.pageX;
var y=event.pageY;
var job="";
for(var i in clickarray){
if(x>=clickarray[i][0] && x<=clickarray[i][2] && y>=clickarray[i][1] && y<=clickarray[i][3] && clickarray[i][5]==1){
job=clickarray[i][4];
clickarray[i][5]=0;//set to allready clicked
break;
}
}
if(job.length>0){
// --do some thing with the job --
}
});
This function proofs the coordinates of a body click event or whether it was already clicked and returns the name attribute. I think it is not necessary to go deeper, but you see it is not that complicate.
Hope in was enlish...
Another idea to try (situationally) would be to:
Put the content you want in a div;
Put the non-clicking overlay over the entire page with a z-index higher,
make another cropped copy of the original div
overlay and abs position the copy div in the same place as the original content you want to be clickable with an even higher z-index?
Any thoughts?
I think the event.stopPropagation(); should be mentioned here as well. Add this to the Click function of your button.
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Just wrap a tag around all the HTML extract, for example
<a href="/categories/1">
<img alt="test1" class="img-responsive" src="/assets/photo.jpg" />
<div class="caption bg-orange">
<h2>
test1
</h2>
</div>
</a>
in my example my caption class has hover effects, that with pointer-events:none; you just will lose
wrapping the content will keep your hover effects and you can click in all the picture, div included, regards!
An easier way would be to inline the transparent background image using Data URIs as follows:
.click-through {
pointer-events: none;
background: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7);
}
I think that you can consider changing your markup. If I am not wrong, you'd like to put an invisible layer above the document and your invisible markup may be preceding your document image (is this correct?).
Instead, I propose that you put the invisible right after the document image but changing the position to absolute.
Notice that you need a parent element to have position: relative and then you will be able to use this idea. Otherwise your absolute layer will be placed just in the top left corner.
An absolute position element is positioned relative to the first parent
element that has a position other than static.
If no such element is found, the containing block is html
Hope this helps. See here for more information about CSS positioning.
You can place an AP overlay like...
#overlay {
position: absolute;
top: -79px;
left: -60px;
height: 80px;
width: 380px;
z-index: 2;
background: url(fake.gif);
}
<div id="overlay"></div>
just put it over where you dont want ie cliked. Works in all.
This is not a precise answer for the question but may help in finding a workaround for it.
I had an image I was hiding on page load and displaying when waiting on an AJAX call then hiding again however...
I found the only way to display my image when loading the page then make it disappear and be able to click things where the image was located before hiding it was to put the image into a DIV, make the size of the DIV 10x10 pixels or small enough to prevent it causing an issue then hiding the containing div. This allowed the image to overflow the div while visible and when the div was hidden, only the divs area was affected by inability to click objects beneath and not the whole size of the image the DIV contained and was displaying.
I tried all the methods to hide the image including CSS display=none/block, opacity=0, hiding the image with hidden=true. All of them resulted in my image being hidden but the area where it was displayed to act like there was a cover over the stuff underneath so clicks and so on wouldn't act on the underlying objects. Once the image was inside a tiny DIV and I hid the tiny DIV, the entire area occupied by the image was clear and only the tiny area under the DIV I hid was affected but as I made it small enough (10x10 pixels), the issue was fixed (sort of).
I found this to be a dirty workaround for what should be a simple issue but I was not able to find any way to hide the object in its native format without a container. My object was in the form of etc. If anyone has a better way, please let me know.
I couldn't always use pointer-events: none in my scenario, because I wanted both the overlay and the underlying element(s) to be clickable / selectable.
The DOM structure looked like this:
<div id="outerElement">
<div id="canvas-wrapper">
<canvas id="overlay"></canvas>
</div>
<!-- Omitted: element(s) behind canvas that should still be selectable -->
</div>
(The outerElement, canvas-wrapper and canvas elements have the same size.)
To make the elements behind the canvas act normally (e.g. selectable, editable), I used the following code:
canvasWrapper.style.pointerEvents = 'none';
outerElement.addEventListener('mousedown', event => {
const clickedOnElementInCanvas = yourCheck // TODO: check if the event *would* click a canvas element.
if (!clickedOnElementInCanvas) {
// if necessary, add logic to deselect your canvas elements ...
wrapper.style.pointerEvents = 'none';
return true;
}
// Check if we emitted the event ourselves (avoid endless loop)
if (event.isTrusted) {
// Manually forward element to the canvas
const mouseEvent = new MouseEvent(event.type, event);
canvas.dispatchEvent(mouseEvent);
mouseEvent.stopPropagation();
}
return true;
});
Some canvas objects also came with input fields, so I had to allow keyboard events, too.
To do this, I had to update the pointerEvents property based on whether a canvas input field was currently focused or not:
onCanvasModified(canvas, () => {
const inputFieldInCanvasActive = // TODO: Check if an input field of the canvas is active.
wrapper.style.pointerEvents = inputFieldInCanvasActive ? 'auto' : 'none';
});
it doesn't work that way. the work around is to manually check the coordinates of the mouse click against the area occupied by each element.
area occupied by an element can found found by 1. getting the location of the element with respect to the top left of the page, and 2. the width and the height. a library like jQuery makes this pretty simple, although it can be done in plain js. adding an event handler for mousemove on the document object will provide continuous updates of the mouse position from the top and left of the page. deciding if the mouse is over any given object consists of checking if the mouse position is between the left, right, top and bottom edges of an element.
Nope, you can't click ‘through’ an element. You can get the co-ordinates of the click and try to work out what element was underneath the clicked element, but this is really tedious for browsers that don't have document.elementFromPoint. Then you still have to emulate the default action of clicking, which isn't necessarily trivial depending on what elements you have under there.
Since you've got a fully-transparent window area, you'll probably be better off implementing it as separate border elements around the outside, leaving the centre area free of obstruction so you can really just click straight through.

jQuery - Selecting a child div background image and amending it

Im looking for a way to change the background image of a div using jQuery BUT only amending it, not totally changing it.
Let me explain.
Im using http://jqueryui.com/demos/sortable/#portlets to show some div's that open and close. Now when you click the portlet header it opens and closes the content below.
Inside the portlet header i have a child div which shows an arrow (either up or down) depending on the current state of the content. I need a way of changing the background image on this child div by adding on "-visible" onto the end of the url for the background image.
I wouldnt even know where to start with doing this, but i have added some code below for you to look at.
http://jsfiddle.net/45jZU/
From the fiddle there, i need to alter the background image of the portlet-arrow div inside portlet header. I can not simply change the background image all together, but i have simplified it down to post on here.
I hope this isnt too narrow to not be of use to anyone else on stackoverflow.
Thanks
Maybe I'm missing something here, but can't you use the .css attribute modifier for the selected jQuery object? Something like:
var current_background = $("#my-div").css("background-image");
$("#my-div").css("background-image", current_background + "-visible");
If you're looking to modify the class names themselves, you can try mess around with the .toggleClass(), .hasClass(), .addClass() and .removeClass() methods in jQuery.
I hope this helps, but let me know if I've missed the mark here completely!
I would personnaly go for using css classes to change the background image. If you decide to change the image afterwards, you won't have to alter your javascript. It is a better solution to use javascript to code the behavior of the widget, not the visual aspect.
So you have the following css:
.portlet-header {
background-image: url(<an image>);
}
.portlet-header.collapsed {
background-image: url(<an other one>);
}
Add this line to your javascript to toggle the collapsed class:
$(".portlet-header").click(function() {
...
$(this).parent().toggleClass('collapsed');
});
If you widgets starts collapsed, initially add the class.
DEMO

JavaScript Cursor Change (and change back again)

I have this page that does some funky database stuff that takes a couple seconds to process, and in the meantime I'd like to set a "wait" cursor so the user doesn't flip out and keep clicking the button. I've looked at the
document.body.style.cursor = "wait"
thing, the problem with this is that it only works when the mouse is over the body of the page (i.e. still shows normal pointer if it's over a button). How can I set it so that no matter where the mouse is on the page, it shows a wait icon?
A second part to this question is, once it's done it's thing, how do I set it back? If I set it back to "default", this seems to override any "hover" cursor changes I had set in my CSS (so it no longer becomes a hand when over a specified object, etc.).
EDIT: the first answer works nicely, except in IE it doesn't refresh the cursor (so you notice the change of cursor type) until you actually move the cursor. Any fixes?
What I suggest is two things:
a) Better write a CSS like
body.waiting * { cursor: wait; }
b) Use the JS to handle the body class
/* when you need to wait */
document.body.className = 'waiting';
/* to remove the wait state */
document.body.className = ''; // could be empty or whatever you want
You might want to add the class instead of replace the whole class attribute, what I suggest is to use something like jQuery for that.
EDIT 2019: don't use jQuery for just this, use classList
The styling should be handled via CSS, as stated by W3C.com:
CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. ... The separation of HTML from CSS makes it easier to maintain sites, share style sheets across pages, and tailor pages to different environments. This is referred to as the separation of structure (or: content) from presentation.
As suggested by Tom Rogerro, add a line to your CSS file:
body.waiting * { cursor: wait; }
However, your script should not overwrite the entire list of class names. Tom suggested setting the class names via jQuery, but jQuery is unnecessary in this case. Simple Javascript can do this.
To add a class name 'waiting' to the document body:
document.body.classList.add('waiting');
To remove a class name 'waiting' from the document body:
document.body.classList.remove('waiting');
For your first problem, try using cursor: wait !important;.
For your second problem, the default cursor for elements is cursor: auto;, not cursor: default; or cursor: inherit;.
If you are happy using JQuery then a quick way to solve this would be to use:
$('*').css('cursor','wait')
I don't know how elegant this is but it has been working for me,
Not an answer to the question, but a way of achieving what is wanted.
Make a div (see class below) visible when you are loading.
ensures no element is accessible and dimmed display indicates this.
you can add an animated gif to indicate something is going on instead of the cursor.
.loading{
position:fixed;
height:100%;
width:100%;
left:0;
top:0;
cursor:wait;
background:#000;
opacity:.5;
z-index:999}
Any elements that don't inherit the cursor by default (such as buttons) will need to set the cursor to inherit:
someButton.style.cursor = 'inherit';
To go back to the default for an element (and not break things like :hover with a forced cursor), set it to an empty string:
document.body.style.cursor = '';
I tried everything but finally this jquery worked, especially if you want wait cursor over all elements including buttons and links.
define at the top of angular .ts file
declare var $: any;
and then where ever you want wait cursor:
$('*').css('cursor','wait');
and remove wait:
$('*').css('cursor','auto');
To fully replace the CSS toggling behaviour, we can simply use this inline:
<img
src=https://cdn.sstatic.net/Img/unified/sprites.svg
onmouseover="this.style.cursor = 'crosshair'"
>

Categories

Resources