I want to rotate an image every time I click on it.. I've created a function to do this but the image only rotate the first time I click on it... Moreover, once the image rotate it change automatically the width and height.. How can I keep the same width and height every time??
This is the function:
$(document).ready(function () {
$("img").click(function () {
$(this).rotate(45)
})
})
This can easily be done by using just javascript, working example would be like this
<div id="imgWrapper">
<img src="Desert.jpg" id="image" onclick="rotateBy10Deg(this)">
</div>
<script>
var delta =0;
function rotateBy10Deg(ele){
ele.style.webkitTransform="rotate("+delta+"deg)";
delta+=10;
}
</script>
The plugin converts the img into a canvas, that's the reason the click not working for second time. Change your jQuery or refer this demo
$(document).ready(function() {
$("img").click(function() {
$(this).rotate(45);
});
$('body').on('click', 'canvas', function() {
$(this).rotate(45);
});
});
I suggest setting max-height and max-width in your CSS file. This will ensure the image doesn't exceed a certain size.
This link might help you out:
Rotate image with onclick
Taken straight from that link in case you don't want to click:
Javascipt
var rotate_factor = 0;
function rotateMe(e) {
rotate_factor += 1;
var rotate_angle = (180 * rotate_factor) % 360;
$(e).rotate({angle:rotate_angle});
}
HTML
<img src='blue_down_arrow.png' onclick='rotateMe(this);' /></a>
I think the angle (45 degree) is calculated in reference to its initial angle that is 0. Once the image is in 45 degree it will only have to rotate if the angle changes (eg 90). So the below code may work
$(document).ready(function () {
var angle = 0;
$("img").click(function () {
angle = angle+45;
$(this).rotate(angle);
})
})
I did it as you suggested, I used css in JQuery:
css:
.rotate:active {
transform: rotate(180deg)
}
JQuery:
$(document).ready(function () {
$("img").click(function () {
//forcing img to rotate every time on click()
if ($(this).css("transform")=='none') {
$(this).css("transform", "rotate(180deg)");
}
else {
$(this).css("transform","")
}
})
})
Related
I want to create a website with background images that change over time with a fade in/fade out effect, but I don't want to use the existing jQuery fade in/fade out effect because with when one image faded out, a white background appeared before other image faded in. I found a plugin named Maximage that suits my request but it uses img tags while I want to work with background-image CSS (I have a good reason for doing this). Does anyone know how to do this?
Here's my HTML code:
<div id="wrapper">
//My contain here
</div>
Here's my JavaScript code so far:
//Auto change Background Image over time
$(window).load(function() {
var images = ['img/top/bg-1.jpg','img/top/bg-2.jpg','img/top/bg-3.jpg'];
var i = 0;
function changeBackground() {
$('#wrapper').fadeOut(500, function(){
$('#wrapper').css('background-image', function () {
if (i >= images.length) {
i = 0;
}
return 'url(' + images[i++] + ')';
});
$('#wrapper').fadeIn(500);
})
}
changeBackground();
setInterval(changeBackground, 3000);
});
Example: http://www.aaronvanderzwan.com/maximage/examples/basic.html
AHH ! Finally ! I found a nice technique ! I'm using a double wrapper.
The problem in your code is a bit logical. You can't fadeOut and fadeIn at the same time a single wrapper.
So the idea is to create two wrapper and to switch between them back and forth. We have one wrapper called: "wrapper_top" that encapsulate the second wrapper called: "wrapper_bottom". And the magic was to put beside the second wrapper: your content.
Thus having the structure ready which is the following:
<div id='wrapper_top'>
<div id='content'>YOUR CONTENT</div>
<div id='wrapper_bottom'></div>
</div>
Then a bit of JS+CSS and voilà ! It will be dynamic with any amount of images !!!
Here is the implementation: http://jsbin.com/wisofeqetu/1/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var i =0;
var images = ['image2.png','image3.png','image1.png'];
var image = $('#slideit');
//Initial Background image setup
image.css('background-image', 'url(image1.png)');
//Change image at regular intervals
setInterval(function(){
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images [i++] +')');
image.fadeIn(1000);
});
if(i == images.length)
i = 0;
}, 5000);
});
</script>
</head>
<body>
<div id="slideit" style="width:700px;height:391px;">
</div>
</body>
</html>
If it doesn't have to be background-image, you can place all the images in your #wrapper, in <img>, it will work like a charm:
<div id="wrapper">
<img src="firstImage" class="imageClass"></img>
<img src="secoundImage" class="imageClass"></img>
<img src="thirdImage" class="imageClass"></img>
</div>
then some style. Every image has to be in same spot, so add position relative to #wrapper, and position absolute to .imageClass:
#wrapper{
position: relative;
}
.imageClass{
position: absolute;
top: 0;
left: 0;
display: none;
}
display: none; will hide every image.
Now some JQuery. To appear first image when window load write this:
$(window).load(function() {
$('.imageClass').eq(0).show();
});
by the .eq() "command" you can specify which one element with class '.imageClass' you want to use exactly. Starts with 0. After that just do something like that:
function changeBackground() {
var current = 0;
//tells which image is currently shown
if(current<$('.imageClass').length){
//loop that will show first image again after it will show the last one
$('.imageClass').eq(current).fadeOut(500);
current++;
$('.imageClass').eq(current).fadeIn(500);
} else {
$('.imageClass').eq(current).fadeOut(500);
current=0;
$('.imageClass').eq(current).fadeIn(500);
}
}
changeBackground();
setInterval(changeBackground, 3000);
});
That should work, hope you will like it.
You may also use jQuery plugin backstretch.
For a very specific project, I need my image captions to appear AND Disappear every X seconds. I managed to make them appear and disappear once, but I need to to "loop". Here's my code :
<figure>
<img src="http://url/image.jpg" alt="Write your image description here" width="400" height="600">
<figcaption class="test">Write your image caption here!</figcaption>
</figure>
Jquery :
document.createElement('figure');
document.createElement('figcaption');
window.setInterval(function(){$(document).ready(function(){
$('figcaption').css('top','600px');
$('figure')(function(){
$(this).find('figcaption').animate({'top':'600px'}, 2000, function(){});
},function(){
$(this).find('figcaption').animate({'top':'540px'}, 2000, function(){});
}
);
});
}, 500);
How can I do it ?
Thanks (a lot) in advance !
Try this:
setInterval(function () {
$('figcaption').fadeToggle();
}, 5000);
Fiddle
EDIT
Updated the fiddle to match your markup.
You certainly want to do something like that:
$(document).ready(function() {
var figcaption = $('figcaption');
setInterval(function() {
figcaption.hide().delay(5000).show();
}, 10000);
});
or:
document.createElement('figure');
document.createElement('figcaption');
$(document).ready(function() {
var figcaption = $('figcaption');
figcaption.css('top', '600px');
window.setInterval(function() {
figcaption
.animate({'top':'600px'}, 2000)
.delay(3000)
.animate({'top':'540px'}, 2000)
;
}, 10000);
});
window.setInterval(function() {
$('figcaption').slideToggle();
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<figure>
<img src="http://url/image.jpg" alt="Write your image description here" width="50" height="50">
<figcaption class="test">Write your image caption here!</figcaption>
</figure>
In your current code, you attach a new method to the document load event every half second. Instead, initialize the interval only once on document load:
$(document).ready(function(){
window.setInterval(function(){
$('figcaption').css('top','600px');
// This call below seems a bit weird. Not sure what you try to accomplish
$('figure')(
function(){
$(this).find('figcaption').animate({'top':'600px'}, 2000, function(){});
},
function(){
$(this).find('figcaption').animate({'top':'540px'}, 2000, function(){});
}
);
}, 500);
});
I'm not to sure about the code inside that function, but without more context I find it a bit hard to judge whether that will work or not.
Instead of hiding it completely through JavaScript, you can define a transition in CSS as well. You can call toggleClass to add and remove a CSS class to the element, or you can even define an infinite animation in CSS itself. This technique is asked for and demonstrated in this answer.
This is the function can do more than you expected:
function blink(elem, times, speed) {
if (times > 0 || times < 0) {
if ($(elem).hasClass("blink")) $(elem).removeClass("blink");
else $(elem).addClass("blink");
}
clearTimeout(function () {
blink(elem, times, speed);
});
if (times > 0 || times < 0) {
setTimeout(function () {
blink(elem, times, speed);
}, speed);
times -= .5;
}
}
And you can use it as:
$(document).ready(function () {
blink(".test", 4, 500);
});
See complete JSFiddle in: http://jsfiddle.net/jadendreamer/Nx4qS/
Hope this help.
Edit:
For using animate function see this post: How to create a jQuery button with blinking text without changing the background colour?
What I'm trying to do is that when the page loads I'm resetting an image to my desired small size.
If the user clicks on the image later it should enlarge with an animation, I'm done up to this part.
When the user again clicks on that image it should be resized to the size that I assigned after loading the page, I have tried toggle event, but that's not working, toggle just makes my images disappear from the page. So I created an alternate to toggle event by using if and else condition and a flag variable called "small" but the problem is that click event is working only once i.e: If the image is in the small size and I click on it, the image gets enlarged but when I click on it again the click event is fired but it doesn't work, I wish if there is any way that I could make it work with toggle event, otherwise I would like to do it by using if and else condition in click event.
Here's the HTML:
<html>
<head>
<title></title>
<script src="jquery-1.10.1.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<img src="wordpress.jpg" class="small-Img" id="test"> <br>
<img src="store.jpg" class="small-Img">
</body>
</html>
Here's the script:
$(document).ready(function() {
var small;
$('.small-Img').on('load',function(){
$(".small-Img").attr('width','200');
small=Number(1);
});
$('.small-Img').on('click',function () {
alert("event fired");
if(small==1){
var obj=$(this);
var originalWidth=obj[0].naturalWidth;
var originalHeight=obj[0].naturalHeight;
$(this).animate({ height: originalHeight, width: originalWidth }, 1000, function() { });
small=Number(0);
}
if(small==0){
$(".small-Img").attr('width','200');
small=Number(1);
}
});
});
Your code
$(".small-Img").attr('width','200');
sets a width attribute on the image, similar to <img src="url" width="200"> which probably doesn't result in a size change. Try
$('.small-Img').css('width','200px');
or animate the shrinking
$('.small-Img').animate({ width: '200px' }, 1000);
You may also get better results making small an attribute of your image rather than a property of the window object
jsfiddle
It sounds like the problem isn't that the event isn't fired multiple times, but that it doesn't enter your if statement. Try making small a boolean variable instead of a number, that way you can avoid all the == vs === messyness
EDIT:
Also, you probably want an else if so that it doesn't shrink once it enlarges on each click.
DEMO
for setting or getting css value we use .css() not .attr()
== only checks the value
=== checks the value and the datatype
$(document).ready(function () {
var small;
$('.small-Img').on('load', function () {
$(".small-Img").css('width', '200'); //changed attr to css
small = 1;
});
$('.small-Img').on('click', function () {
if (small === 1) { //changed == to ===
var obj = $(this);
var originalWidth = obj[0].naturalWidth;
var originalHeight = obj[0].naturalHeight;
$(this).animate({
height: originalHeight,
width: originalWidth
}, 1000, function () {});
small = 0;
}
if (small === 0) { //changed == to ===
$(".small-Img").css('width', '200'); //changed attr to css
small = 1;
}
});
});
How about first making "small" a data-attribute on the image itself? Not a big deal, but a little more convenient (IMHO). The next thing is, when you want to check the second click, you might consider doing an else if rather than just an if. Not sure if it makes a difference, but it is a clear logical differentiation, you can have one or the other -- not both. Third, if you animate the width back down, you might also animate the height, calculated by your small height divided by your original height times the original width. Seems to work, see it here: http://jsfiddle.net/snowMonkey/7nCMF/1/
$('.small-Img').css('width','200px').data("small", 1);
$('.small-Img').on('click',function () {
var that=this;
this.smallWidth = "200px";
this.smallHeight = (200/$(this)[0].naturalWidth) * $(this)[0].naturalHeight+"px";
if($(this).data("small")===1 ){
var obj=$(that);
var originalWidth=obj[0].naturalWidth;
var originalHeight=obj[0].naturalHeight;
$(that).animate({
height: originalHeight,
width: originalWidth
}, 1000, function() { });
$(that).data("small",0);
} else if($(this).data("small")===0){
$(that).animate({
width: that.smallWidth,
height: that.smallHeight
}, 1000, function(){}).data("small", 1);
}
});
Best of luck!
I'm trying to hide the mouse if it hasn't moved for a period of time.
This is the code I'm using:
$(document).ready(function() {
var j;
$(document).mousemove(function() {
clearTimeout(j);
$('html').css({cursor: 'default'});
j = setTimeout('hide();', 1000);
});
});
function hide() {
$('html').css({cursor: 'none'});
}
When the hide() function is called the cursor is hidden, but unhides a split second later. Any help is appreciated.
Your initial problem is that the hiding of the mouse triggers mousemove and thus immediately resets it back to default. So you could solve that like this...
var justHidden = false;
$(document).ready(function() {
var j;
$(document).mousemove(function() {
if (!justHidden) {
justHidden = false;
console.log('move');
clearTimeout(j);
$('html').css({cursor: 'default'});
j = setTimeout('hide();', 1000);
}
});
});
function hide() {
$('html').css({cursor: 'none'});
justHidden = true;
}
...BUUUUUT...
You face a problem here which at the moment seems unsolvable to me. That is, a hidden mouse does not trigger mousemove ever, so once it's hidden you will not be able to unhide it as far as I can tell.
I'll keep investigating to see if there's a solution I'm missing.
I found this thread when I was looking for solution for this challenge in 2019. Based on answer here and in 'Hiding the mouse cursor when idle using JavaScript' I made a slightly different solution:
var DEMO = {
INI: {
MOUSE_IDLE: 3000
},
hideMouse: function() {
$("#game").css('cursor', 'none');
$("#game").on("mousemove", DEMO.waitThenHideMouse);
},
waitThenHideMouse: function() {
$("#game").css('cursor', 'default');
$("#game").off("mousemove", DEMO.waitThenHideMouse);
setTimeout(DEMO.hideMouse, DEMO.INI.MOUSE_IDLE);
},
showMouse: function() {
$("#game").off("mousemove", DEMO.waitThenHideMouse);
$("#game").css('cursor', 'default');
},
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This simple and clear example gives you the option to start hiding mouse (DEMO.hideMouse()) and also to turn this off (DEMO.showMouse()). It does not create multiple events on same element. This example shows hiding mouse pointer over #game div element. Just change this to the div of your choice or body.
As of fully updated Chrome and FF in October 2019: it works on both.
I'm 8 years late but I have a solution:
• First of all download an image of a cursor from the internet or copy my svg code:
<svg id="cursor" width="20" height="20" viewBox="0 0 95 92" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M84.6925 46.0105L40.25 20.3516C35.25 17.4648 29 21.0733 29 26.8468L29 78.1645C29 84.9879 37.3721 88.2664 42.0056 83.2575L58.1424 65.8134C58.4853 65.4427 58.9324 65.1846 59.4249 65.0729L82.6003 59.8201C89.255 58.3118 90.6017 49.4222 84.6925 46.0105Z" fill="black" stroke="white" stroke-width="5"/></svg>
And add it to your html file.
•Of course, if you want to made it in jQuery, you need to add this script above your js file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
•Then add this (in your JavaScript file):
let timedelay = 1;
function delayCheck() {
if (timedelay == 2) { //Here you can change this value which changes the time it takes the mouse to hide
$('#cursor').fadeOut();
timedelay = 1;
}
timedelay += 1;
}
$(document).mousemove(function() {
$('#cursor').fadeIn();
timedelay = 1;
clearInterval(_delay);
_delay = setInterval(delayCheck, 1000);
});
_delay = setInterval(delayCheck, 1000);
Now you'll see just a cursor on the top left of the screen that does what you asked but it's not YOUR cursor, to replace the cursor with the svg do the following:
//in the same js file as before
$(document).mousemove(function (e) {
$('#cursor').offset({
left: e.clientX,
top: e.clientY
});
});
/* on the css */
html {
cursor: none;
}
If it doesn't work, make sure that you put the jquery file ABOVE the file you wrote.
I hope I have helped someone!
You might want to check if this really works, here's the demo.
(Sorry if my English was bad, I'm italian).
(Tip) You will notice that there are two identical functions, if you want to merge them just replace them with this:
$(document).mousemove(function(e) {
$('#cursor').fadeIn();
timedelay = 1;
clearInterval(_delay);
_delay = setInterval(delayCheck, 1000);
$('#cursor').offset({
left: e.clientX,
top: e.clientY
});
});
I have some simple code to replace an image src. It is working correctly but everytime the image is updated, the browser skips right back to the top of the page.
I have several image tags in my page. All of which hidden, except for the first one. The script just iterates through them and uses the src attribute to update the first image.
Here is the code I am using:
var j = jQuery.noConflict();
var count = 1;
var img;
function update_main_image()
{
count++;
if (j('#main_image_picture_'+count).length > 0)
{
img = j('#main_image_picture_'+count).attr('src');
}
else
{
count = 1;
img = j('#main_image_picture_'+count).attr('src');
}
j(".main_image_picture_auto").fadeOut(1500, function() {
j(this).fadeIn();
j(this).attr("src", img);
});
}
j(document).ready(function()
{
setInterval(update_main_image, 6000);
});
Any ideas what might be causing it?
Any advice appreciated.
Thanks.
Try to add DIV around your IMG.main_image_picture_auto with width and height style properties setted to maximum posible image size, for example:
<div style='width:400px; height:400px; border: 0px; background: transparent; '>
<img class='main_image_picture_auto' src=''/>
</div>
<!-- Where width:400px and height:400px is maximum allowed image size -->
And I think, that is better to use setTimeout instead of setInterval
function update_main_image() {
// ....
setTimeout(update_main_image, 6000);
}
j(document).ready(function() {
setTimeout(update_main_image, 6000);
});
http://jsfiddle.net/UBEWS/