How to change the mouse pointer? - javascript

I need to change the mouse pointer to the wait cursor. I tried
document.body.style.cursor = 'wait';
In my fiddle, my mouse cursor does not change (nor does it change in my main app). I tried a couple methods, but nothing seems to work (IE7 and FF7 tested). How do I change the cursor? I am open to using CSS instead of JavaScript if that works better.
For what it is worth...In the final program, I need to change the pointer at the start of an AJAX call and then change it back to the default in the callback. But, this is a simplified example and still does not work.

I'd create a CSS class:
.busy {
cursor: wait !important;
}
and then assign this class to body or whatever element you want to mark as busy:
$('body').addClass('busy');
// or, if you do not use jQuery:
document.body.className += ' busy';
http://jsfiddle.net/ThiefMaster/S7wza/
If you need it on the whole page, see Wait cursor over entire html page for a solution

Since there is no text you don't really have a body (in terms of "it has no height").
Try adding some content and then hovering the text: http://jsfiddle.net/kX4Es/4/. You can just use CSS.
Or, add it to the <html> element to bypass this <body> constraint: http://jsfiddle.net/kX4Es/3/.
html {
cursor: wait;
}

Like this:
$('html').css('cursor', 'wait');
Or as a CSS class as said above by ThiefMaster

I only tried this in chrome and firefox so it may not work everywhere.
But if you want to do this with javascript and turn it on and off try this.
//add
document.styleSheets[1].insertRule('html {cursor:wait;}',document.styleSheets[1].cssRules.length);
//for firefox I had to tell it to fill the screen with the html element
//document.styleSheets[1].insertRule('html {height:100%;width:100%;cursor:wait;}',0);
//remove
document.styleSheets[1].deleteRule(document.styleSheets[1].cssRules.length-1);
http://www.quirksmode.org/dom/w3c_css.html#access seems to be a good reference on messing around with the actual stylesheets. I was hoping for a better way to edit the html elements style but this was all I could find...

are you declaring it as a function ?
function cursor_wait() {
document.body.style.cursor = 'wait';
}
then call
cursor_wait();
in your script ?

Related

Change image and Text on Scroll (Javascript)

I dont have much experience in javascript but trying to achieve a slideshow like in https://district2.studio/ where the text and image changes as you scroll. In the example no matter the amount you scroll at a time or inbetween the image changing animation, the image will change only once at a time. I'm trying to achieve this using javascript only and no additional plugin or libraries. Hope someone can help me.
You have some errors.
First of all, you have to wait the DOM is ready. You could movet he entire before de body tag closes to ensure that or use window.onload
class prop elements it's an array.
window.onload = function() {
document.getElementById("image1").onscroll = function() {
if(document.getElementById("image2").classList.contains("scroll")){
document.getElementById("image2").classList.remove("scroll");
} else {
document.getElementById("image2").classList.add("scroll");
}
};
}
Something like this should work

Chrome ignoring hashes in URL

I've spent quite a while trying to find answers for this issue, but haven't had any success. Basically I need to scroll the user to the contact portion of the website when they go to healthdollars.com/#contact. This works just fine in Safari, but in Chrome I haven't had any luck. I've tried using jQuery/Javascript to force the browser to scroll down, but I haven't been able to.
Does anyone have any ideas? It's driving me crazy - especially since it's such a simple thing to do.
Not a full answer but in Chrome if you disable Javascript I believe you get the desired behavior. This makes me believe that something in your JavaScript is preventing default browser behavior.
It looks to me like the target element doesn't exist when when page first loads. I don't have any problem if I navigate to the page and then add the hash.
if (window.location.hash.length && $(location.hash)) {
window.scrollTo(0, $(location.hash).offset().top)
}
check for a hash, find the element's page offset, and scroll there (x, y).
edit: I noticed that, in fact, the page starts at #contact, then scrolls back to the top. I agree with the other answerer that there's something on your page that's scrolling you to the top. I'd search for that before adding a hack.
You can do this with JS, for example` if you have JQuery.
$(function(){
// get the selector to scroll (#contact)
var $to = $(window.location.hash);
// jquery animate
$('html'/* or body */).animate({ scrollTop: $to.offset().top });
});
The name attribute doesn't exists in HTML 5 so chrome looks to have made the name attribute obsolete when you use the DOCTYPE html.
The other browsers have yet to catch up.
Change
<a name="contact"></a>
to
<a id="contact"></a>
Maybe this workaround with vanilla javascript can be useful:
// Get the HTMLElement that you want to scroll to.
var element = document.querySelector('#contact');
// Stories the height of element in the page.
var elementHeight = element.scrollHeight;
// Get the HTMLElement that will fire the scroll on{event}.
var trigger = document.querySelector('[href="#contact"]');
trigger.addEventListener('click', function (event) {
// Hide the hash from URL.
event.preventDefault();
// Call the scrollTo(width, height) method of window, for example.
window.scrollTo(0, elementHeight);
})

div onclick function to change body background image

I want a small picture that acts like a button, to be click-able with a function to change the body background-image. I am a total newbie and I'm trying to learn. The most simple way, I thought, would be to have a div with a background-image.
I have to use unsemantic grid, also.
So I pretty much only have the div with a background image. How do I write this function? I'm sure it's really easy and I've read like 20 threads here but none of them were useful for me
Edit: added my code
#knapp {
height:50px;
width:50px;
background-image:url(http://ingridwu.dmmdmcfatter.com/wp-content/uploads/2015/01/placeholder.png);
background-repeat:no-repeat;
background-size:contain;
position:absolute;
top:90vh;
right:3vw;
}
<div id="knapp" class="grid-10 prefix-90"></div>
Add cursor on the div to appear clickable
#knapp {
cursor: pointer;
}
You could put the new background-image in a new css rule
body.newbg {
background-image:url(path-to-new-background.png);
}
This is body with the old background-image
body {
background-image:url(path-to-old-background.png);
}
and with jquery just add/toggle the class by doing something like that (in $(document).ready()):
$('#knapp').on('click', function(){
$('body').addClass('newbg');
// you could instead do toggleClass if you want for each click to have background switch between old background and new background
});
This is a cleaner approach compared to all the other answers as it separates presentation (css), structure (html) and behavior (javascript).
This is because it doesn't use JavaScript to change style directly. Also it doesn't pollute html with onclick which is also a bad practice.
Here is a plunkr: https://plnkr.co/edit/aiGZmvvi6WWGFs7E9xTp
and here is one with a circular collection of backgrounds (thanks to Kai's idea)
https://plnkr.co/edit/0djmmNM9OOTdfYyvLvUH?p=preview
Create a button with onclick attribute with a function name like replace.
Defined the function in your script like:
function replace() {
document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';
}
Explanation:
You set the style property of the body (using document.body object) to other background-image.
If something is not clear, I will happy to explain.
Working example:
function replace() {
document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)';
}
body {
background-image: url(http://www.julienlevesque.net/preview/google-smile-preview.jpg);
}
div {
background:blue;
color:#fff;
float:left;
}
<div onclick="replace()">Replace background-image</div>
This may help you...
$('.yourClassofDiv').click({
$(this).css("background-image",'url("' + URLofIMAGE+ '")')
});
Try using onclick at div#knapp element , set document.body.style.background to url of image file
#knapp {
height:50px;
width:50px;
background-image:url(http://lorempixel.com/50/50);
background-repeat:no-repeat;
background-size:contain;
position:absolute;
top:90vh;
right:3vw;
}
<div id="knapp" class="grid-10 prefix-90" onclick="document.body.style.background = 'url(http://lorempixel.com/'+ window.innerWidth + '/'+ window.innerHeight +') no-repeat'"></div>
here is a simple way in jquery
$(document).ready(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');
$('div').css('cursor', 'pointer').click(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
<div style="background-color:yellow">Click Here to change background Image</div>
</body>
Here i will explain the code.
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s).
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
Here is what happen in the code.
1.
$(document).ready(function(){
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.
2
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');
getting the body element of your html and set its background-image with .css() action. which i gave it more one action
3
$('div').css('cursor', 'pointer').click(function() {
$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
});
this is where the change takes place. i got the div to be clicked by $('div') and first gave it an action of changing the mouse to cursor to indicate its clickable and then gave it the click function, where our background-image get changed on click
If I understand the question, you should be able to create a variable in jQuery which is an array of all the string versions of your image urls that you want to use:
var images = ['../images/####','../images/$$$$', 'http://some.other/url.here];
// do this for as many images as you want to cycle through
Like that.
Then you can make a counter variable:
var counter = 0;
and set it to zero.
Next, add the event listener on() to your div like this:
$('#knapp').on('click', function(){
});
Finally, inside your event listener, change the CSS background-image property of the div to one of your images in the array:
// do this inside a document.ready() function
$('#knapp').on('click', function(){
$(this).css('background-image','url("' + images[counter] + '")');
counter++;
});
I hope this helped! Also, remember to increment counter
EDIT ----------------------------------------------------------------
OK, so I totally jumped over something obvious which is the fact that the counter might go too high and access something out of scope. To prevent this add the following inside of your on() listener:
if(counter >= images.length - 1){
counter = 0;
}
EDIT 2 --------------------------------------------------------------
Ok, so I didn't know what exactly you were asking at first, so here is my second answer. Since it seems like what you are actually trying to do is only switch the background image once on click, then you could use something like this:
$(document).ready(function(){
$('#knapp').on('click', function(){
$(this).css('background-image','url("YOUR_NEW_URL_HERE")');
});
});
or you could have it toggle between two images by making two identical classes in CSS (except for the background image) and replacing one with the other using .addClass and .removeClass.
EDIT 3---------------------------------------------------------------
I never thought I would edit this post this many times, but apparently I missed that the body background image should be changed (thanks to comments). My bad and thanks for pointing it out (even if you were talking to someone else).

jQuery function doesn't respond to ".click" until I move the cursor?

I have a website with a simple CSS style switcher. I use the following code for the function that handles clicking the two theme buttons, initiating the switch from dark to light and vice versa:
<script>
$(function() {
$(".light").click(function(){
$("link").attr("href", "css/lightHome.css");
$(".light").attr("disabled", "disabled");
$(".dark").removeAttr("disabled", "disabled")
})
$(".dark").click(function(){
$("link").attr("href", "css/home.css");
$(".dark").attr("disabled", "disabled");
$(".light").removeAttr("disabled", "disabled")
})
});
</script>
Everything about it operates exactly as I want, except the fact that when I click the button, nothing happens. But the second I shift the cursor position after the click, then the switch occurs. I don't have the best jQuery grasp, so I am hoping it is a simple lack of understanding regarding the DOM processes. Possibly having to do with the lack of "on ready"?
I've tried clicking and waiting several minutes, and nothing happens until I move the cursor.
The website:
http://watsoncn.info
Instead of completely switching the CSS file, an alternative solution would be to have a single CSS file with both your styles and then prefixing all your selectors with .theme.dark or .theme.light;
This would be pretty easy to do with nesting in LESS or SASS if you're using them (if you're not, you really should consider it. I can't imagine writing CSS without a preprocessor now), but might be cumbersome in pure CSS.
CSS:
.theme.dark <rest of selectors> {
//CSS
}
.theme.light <rest of selectors> {
//CSS
}
HTML:
<body class="theme">
and then code that runs on button clicks would be
$('body').addClass('dark')
$('body').removeClass('light')
and
$('body').addClass('light')
$('body').removeClass('dark')
Try this function:
function toggleCss(file, index) {
var oldFile = document.getElementsByTagName("link").item(index);
var newFile = document.createElement("link");
newFile.setAttribute("rel", "stylesheet");
newFile.setAttribute("type", "text/css");
newFile.setAttribute("href", file);
document.getElementsByTagName("head").item(0).replaceChild(newFile, oldFile);
}
$(".dark").on("click", function() {
toggleCss("css/lightHome.css");
$(".dark").attr("disabled", "disabled");
$(".light").removeAttr("disabled", "disabled");
});
$(".light").on("click", function() {
toggleCss("css/home.css");
$(".light").attr("disabled", "disabled");
$(".dark").removeAttr("disabled", "disabled");
});
Try to add use not a JavaScript, but the "checkbox trick". The checkbox handler set to display none, then style the main style, and on :checked style the handler like it clicked.
With this you can not use JavaScript but make it 100% working without any bugs, if you did everything right!
You can find the DevTips channel on YouTube
https://www.youtube.com/user/DevTipsForDesigners
on his channel you can find the tutorial how to do that!

DIV with an onclick function and an image inside of it has a dead spot

I have a DIV with in image inside of it. There is a spot right before the image that does not fire the onclick function when clicked. The rest, including the image and the DIV fire the function when clicked. I have tried attaching the function to the image itself in addition to the DIV and this does not fix the problem. Anyone know what to do?
//this give all the divs the function
var ButtonNumber = document.querySelectorAll(".ButtonStyle");
for (var i = 0; i < ButtonNumber.length; i++) {
ButtonNumber[i].onmouseover = ChangeCursor;
ButtonNumber[i].onclick = ButtonsAddTogether;
ButtonNumber[i].onselectstart = function() {return false;}
}
This is the HTML
<div id="55" class="ButtonStyle"><img alt="1" class="Center" src="Buttons/7.png"></div>
Try setting the image and the div to have the same height. That or use an inline element rather than a block element such as an anchor tag
I have placed your code within jsfiddle: http://jsfiddle.net/BUwFP/1/
Please look at it and tell me if it works for you. I have just:
defined functions that were not defined (probably you just skipped them showing your code),
added borders to image and the div that contains it,
and everything looks fine - clicking the box etc. fires events. Do similar thing and check whether your box really is placed where you click or somehow it has been moved (probably by CSS styles or JS code). You probably already know, that you may use Firebug in Firefox, Developer Tools in Chrome or anything similar.

Categories