Making a button switch out an image on click - javascript

There may be an easier way to do this, like with CSS, I think, pseudo-classes or whatever
but anyway for some reason I already wrote this function.
On mouseup it should switch the image back to normal. (Note that the images have the same names except for mouse down the .png is switched with ed.png and the opposite is done for document.mouseup. But document.mouseup isn't even working).
$.fn.buttonify = function () {
console.log("buttonification successful");
var that;
var source;
this.mousedown(function (event) {
var top_value;
var left_value;
that = this;
if (event.which == 1) { //if it is a left click
source = this.src.substring(0, this.src.length - 4);
source += "ed.png";
this.src = source;
console.log(this.src);
}
});
$(document).mouseup(function () {
if (that == null) {
console.log("returninurnging");
return;
}
console.log(source);
source = source.substring(0, source.length - 6); //very questionable code
source += ".png";
that.src = source;
console.log(that.src);
that = null;
});
}
When the mouse is lifted outside the click area, it does not change the image.
Otherwise it works. :(

What do U really want?
<img src="image1.jpg" id="image">
<input type="button" value="whatever" onMouseDown="change()" onMouseUp="undochange()">
JAVASCRIPT
function change()
{
image = document.getElementById ("image");
image.src="image2.jpg";
}
function undochange()
{
image = document.getElementById ("image");
image.src="image1.jpg";
}

Related

Not sure how to adapt ancient image switcher code from using name="foo" to id="foo"

About 19 years ago, I needed a script that changes images using the onmouseover event. The script used name="foo" which, of course, can no longer be supported by the <img> tag. I've literally forgotten how the script works and I need some help adapting it to use id="foo".
This is the script that lives in my <head>:
<script>
function newImage(arg) {
if (document.images) {
rslt = new Image();
rslt.src = arg;
return rslt;
}
}
function changeImages() {
if (document.images && (preloadFlag == true)) {
for (var i=0; i<changeImages.arguments.length; i+=2) {
document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
}
}
}
var preloadFlag = false;
function preloadImages() {
if (document.images) {
archives_over = newImage("/images/index/menu/archives_over.jpg");
bio_over = newImage("/images/index/menu/bio_over.jpg");
poetry_over = newImage("/images/index/menu/poetry_over.jpg");
preloadFlag = true;
}
}
</script>
...and this is the HTML that lives in my <body>:
<a href='https://www.foo.com/index.php?page=news'
onmouseover='changeImages("poetry", "/images/index/menu/poetry_over_static.jpg"); return true;'
onmouseout='changeImages("poetry", "/images/index/menu/poetry_over_static.jpg"); return true;'
onmousedown='changeImages("poetry", "/images/index/menu/poetry_over_static.jpg"); return true;'
onmouseup='changeImages("poetry", "/images/index/menu/poetry_over_static.jpg"); return true;'>
<img name="poetry" src="/images/index/menu/poetry_over_static.jpg">
</a>
If I change <img name="poetry" to <img id="poetry", the whole thing stops working.
Your
document[changeImages.arguments[i]]
when the first argument is poetry, accesses document.poetry. Use getElementById instead, to select an element with a particular id:
function changeImages(id, newSrc) {
document.getElementById(id).src = newSrc;
}
You also might consider attaching listeners properly using addEventListener, rather than inline handlers:
const a = <select your <a> tag here>
const img = document.getElementById('poetry');
const fn = () => {
img.src = '/images/index/menu/poetry_over_static.jpg';
}
['mouseover', 'mouseout', 'mousedown', 'mouseup'].forEach((eventType) => {
a.addEventListener(eventType, fn);
});
If you're doing this sort of thing for multiple images on the page, then you can make the code even better by dynamically selecting the <a>'s nextElementSibling, allowing you to avoid IDs entirely:
const fn = ({ target }) => {
const img = target.nextElementSibling;
img.src = '/images/index/menu/poetry_over_static.jpg';
}
['mouseover', 'mouseout', 'mousedown', 'mouseup'].forEach((eventType) => {
a.addEventListener(eventType, fn);
});

How to keep Skrollr-Menu at an even speed?

I'm using Skrollr-menu to animate down a page on a button press using the following
HTML
<div class="trigger-scroll left">></div>
... the page i want to reveal, using scrolling ...
<section id="End" class="scroll-here">
<div class="hsContainer bottom"></div>
</section>
JavaScript
var s = skrollr.init();
skrollr.menu.init(s, {
animate: true,
//How long the animation should take in ms.
duration: function(currentTop, targetTop) {
//By default, the duration is hardcoded at 500ms.
return 18000;
//But you could calculate a value based on the current scroll position (`currentTop`) and the target scroll position (`targetTop`).
//return Math.abs(currentTop - targetTop) * 10;
},
//This event is triggered right before we jump/animate to a new hash.
change: function(newHash, newTopPosition) {
//Do stuff
},
//Add hash link (e.g. `#foo`) to URL or not.
updateUrl: false //defaults to `true`.
});
What happens when I click the button is that it works, that is not the problem.
The problem is that it seems to change speed as skrollr-menu animates the page. It starts off quite quickly, which means that the first few elements on the page (about the first 2000px) flash past without being readable. Then the speed evens out and is fine right until the last 3000px (approximately) where skrollr-menu is very slow. What I want is for the click of the button to resemble holding the down arrow on the keyboard or the scroll sidebar, which by default it seems skrollr-menu does not do.
I've tried using math equations to change the speed but the issue persists no matter what i try, and there doesn't seem to be any "simple" way to change the acceleration speed, and I suspect the problem is somewhere within the Skrollr.menu.js file, but I can't see where.
Is there any way which I can make the scrolling an even speed, rather than fast at the start and slow at the end?
Note: I'm not very experienced in JavaScript or jQuery, so it's probably something simple I've overlooked.
skrollr menu on github
https://github.com/Prinzhorn/skrollr-menu
Skrollr.menu.js
/*!
* Plugin for skrollr.
* This plugin makes hashlinks scroll nicely to their target position.
*
* Alexander Prinzhorn - https://github.com/Prinzhorn/skrollr
*
* Free to use under terms of MIT license
*/
(function(document, window) {
'use strict';
var DEFAULT_DURATION = 500;
var DEFAULT_EASING = 'sqrt';
var DEFAULT_SCALE = 1;
var MENU_TOP_ATTR = 'data-menu-top';
var MENU_OFFSET_ATTR = 'data-menu-offset';
var MENU_DURATION_ATTR = 'data-menu-duration';
var MENU_IGNORE_ATTR = 'data-menu-ignore';
var skrollr = window.skrollr;
var history = window.history;
var supportsHistory = !!history.pushState;
/*
Since we are using event bubbling, the element that has been clicked
might not acutally be the link but a child.
*/
var findParentLink = function(element) {
//We reached the top, no link found.
if(element === document) {
return false;
}
//Yay, it's a link!
if(element.tagName.toUpperCase() === 'A') {
return element;
}
//Maybe the parent is a link.
return findParentLink(element.parentNode);
};
/*
Handle the click event on the document.
*/
var handleClick = function(e) {
//Only handle left click.
if(e.which !== 1 && e.button !== 0) {
return;
}
var link = findParentLink(e.target);
//The click did not happen inside a link.
if(!link) {
return;
}
if(handleLink(link)) {
e.preventDefault();
}
};
/*
Handles the click on a link. May be called without an actual click event.
When the fake flag is set, the link won't change the url and the position won't be animated.
*/
var handleLink = function(link, fake) {
var hash;
//When complexLinks is enabled, we also accept links which do not just contain a simple hash.
if(_complexLinks) {
//The link points to something completely different.
if(link.hostname !== window.location.hostname) {
return false;
}
//The link does not link to the same page/path.
if(link.pathname !== document.location.pathname) {
return false;
}
hash = link.hash;
} else {
//Don't use the href property (link.href) because it contains the absolute url.
hash = link.getAttribute('href');
}
//Not a hash link.
if(!/^#/.test(hash)) {
return false;
}
//The link has the ignore attribute.
if(!fake && link.getAttribute(MENU_IGNORE_ATTR) !== null) {
return false;
}
//Now get the targetTop to scroll to.
var targetTop;
var menuTop;
//If there's a handleLink function, it overrides the actual anchor offset.
if(_handleLink) {
menuTop = _handleLink(link);
}
//If there's a data-menu-top attribute and no handleLink function, it overrides the actual anchor offset.
else {
menuTop = link.getAttribute(MENU_TOP_ATTR);
}
if(menuTop !== null) {
//Is it a percentage offset?
if(/p$/.test(menuTop)) {
targetTop = (menuTop.slice(0, -1) / 100) * document.documentElement.clientHeight;
} else {
targetTop = +menuTop * _scale;
}
} else {
var scrollTarget = document.getElementById(hash.substr(1));
//Ignore the click if no target is found.
if(!scrollTarget) {
return false;
}
targetTop = _skrollrInstance.relativeToAbsolute(scrollTarget, 'top', 'top');
var menuOffset = scrollTarget.getAttribute(MENU_OFFSET_ATTR);
if(menuOffset !== null) {
targetTop += +menuOffset;
}
}
if(supportsHistory && _updateUrl && !fake) {
history.pushState({top: targetTop}, '', hash);
}
var menuDuration = parseInt(link.getAttribute(MENU_DURATION_ATTR), 10);
var animationDuration = _duration(_skrollrInstance.getScrollTop(), targetTop);
if(!isNaN(menuDuration)) {
animationDuration = menuDuration;
}
//Trigger the change if event if there's a listener.
if(_change) {
_change(hash, targetTop);
}
//Now finally scroll there.
if(_animate && !fake) {
_skrollrInstance.animateTo(targetTop, {
duration: animationDuration,
easing: _easing
});
} else {
defer(function() {
_skrollrInstance.setScrollTop(targetTop);
});
}
return true;
};
var jumpStraightToHash = function() {
if(window.location.hash && document.querySelector) {
var link = document.querySelector('a[href="' + window.location.hash + '"]');
if(!link) {
// No link found on page, so we create one and then activate it
link = document.createElement('a');
link.href = window.location.hash;
}
handleLink(link, true);
}
};
var defer = function(fn) {
window.setTimeout(fn, 1);
};
/*
Global menu function accessible through window.skrollr.menu.init.
*/
skrollr.menu = {};
skrollr.menu.init = function(skrollrInstance, options) {
_skrollrInstance = skrollrInstance;
options = options || {};
_easing = options.easing || DEFAULT_EASING;
_animate = options.animate !== false;
_duration = options.duration || DEFAULT_DURATION;
_handleLink = options.handleLink;
_scale = options.scale || DEFAULT_SCALE;
_complexLinks = options.complexLinks === true;
_change = options.change;
_updateUrl = options.updateUrl !== false;
if(typeof _duration === 'number') {
_duration = (function(duration) {
return function() {
return duration;
};
}(_duration));
}
//Use event bubbling and attach a single listener to the document.
skrollr.addEvent(document, 'click', handleClick);
if(supportsHistory) {
skrollr.addEvent(window, 'popstate', function(e) {
var state = e.state || {};
var top = state.top || 0;
defer(function() {
_skrollrInstance.setScrollTop(top);
});
}, false);
}
jumpStraightToHash();
};
//Expose the handleLink function to be able to programmatically trigger clicks.
skrollr.menu.click = function(link) {
//We're not assigning it directly to `click` because of the second ("private") parameter.
handleLink(link);
};
//Private reference to the initialized skrollr.
var _skrollrInstance;
var _easing;
var _duration;
var _animate;
var _handleLink;
var _scale;
var _complexLinks;
var _change;
var _updateUrl;
//In case the page was opened with a hash, prevent jumping to it.
//http://stackoverflow.com/questions/3659072/jquery-disable-anchor-jump-when-loading-a-page
defer(function() {
if(window.location.hash) {
window.scrollTo(0, 0);
}
});
}(document, window));
The problem was the easing function found here
//Now finally scroll there.
if(_animate && !fake) {
_skrollrInstance.animateTo(targetTop, {
duration: animationDuration,
easing: _easing
});
} else {
defer(function() {
_skrollrInstance.setScrollTop(targetTop);
});
}
return true;
It seems that, even though Skrollr states that easing's default is linear (no easing), the default is ACTUALLY set to sqrt (or at least it was in my case). The problem can be solved by forcing easing to linear in skrollr.menu.init, or chaning the skrollr.menu.js file to remove easing from the function. The first of these two solutions is cleaner, and won't cause issues later.
skrollr.menu.init(s, {
duration: function(currentTop, targetTop) {return 20000;},
easing: 'linear'
});

Using Pixastic and .live with a class of images

I'm using the Pixastic plugin in JavaScript. I have a table filled with images that are blurred. When I go over them with the mouse I want them to get normal. And when the mouse leaves an image I want it to blur back. For some reason my code doesn't work. Here's the code:
Before, I copied the wrong code part, and I apologize for that this one is the one I'm asking about.
<script type="text/javascript">
$(document).ready(function(){
$('.photography').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
function () {Pixastic.revert('this');};
}
else {
function(){Pixastic.process('this', "blurfast", {amount:0.5});};
}
});
});
</script>
OK, so I managed to find my old code that actually works half way (when I hover over the image for the first time it works, but when I try for the second time it doesn't).
$(document).ready(function(){
var blur = function() {Pixastic.process(this, "blurfast", {amount:0.5});};
var unblur = function () {Pixastic.revert(this);};
$('.photography').each(blur);
$('.photography').hover(unblur,blur);
});
OK, so now I'm also adding the code for the function called revert:
revert : function(img) {
if (Pixastic.Client.hasCanvas()) {
if (img.tagName.toLowerCase() == "canvas" && img.__pixastic_org_image) {
img.width = img.__pixastic_org_width;
img.height = img.__pixastic_org_height;
img.getContext("2d").drawImage(img.__pixastic_org_image, 0, 0);
if (img.parentNode && img.parentNode.replaceChild) {
img.parentNode.replaceChild(img.__pixastic_org_image, img);;
}
return img;
}
}
else
if (Pixastic.Client.isIE()) {
if (typeof img.__pixastic_org_style != "undefined")
img.style.cssText = img.__pixastic_org_style;
}
}
So yesterday my friend discovered how this could be done ... the problem was that the plugin converts images into canvas anyway her's the code :
$(document).ready(function(){
$('.pic').each(function(){
this.onmouseout = function(){
var canvas1 = Pixastic.process(this, "blurfast", {amount:0.5});
canvas1.onmouseover = function(){
Pixastic.revert(this);
}
}
this.onload = function(){
var canvas = Pixastic.process(this, "blurfast", {amount:0.5});
canvas.onmouseover = function(){
Pixastic.revert(this);
}
}
});
});
Try doing this
$('.photography').live('mouseenter', function(event){
Pixastic.revert(this);
}).live('mouseleave', function(event){
Pixastic.process(this, "blurfast", {amount:0.5});
});

How do I move image in the front of Download Now in javascript code?

How do I move this image http://svastara.info/.s/img/icon/download1.png in the front of Download now?
Should look something like this: image Download Now
var CountdownTimer = function( id, count, imgurl ) { this.construct(id, count, imgurl); }
CountdownTimer.prototype = {
construct: function(id,count,imgurl) {
this.id = id;
this.object = document.getElementById(id);
this.count = count;
this.interval = null;
this.counted = false;
this.img = new Image(); // preload
this.img.src = imgurl;
this.img.border = "0";
(function(obj) {
obj.object.onclick = function() {
return obj.onclick();
};
})(this);
},
tick: function() {
this.count--;
this.render();
if(this.count == 0){
clearInterval(this.interval);
this.interval = null;
this.object.appendChild(this.img);
}
},
onclick: function() {
if(!this.counted) {
this.counted = true;
this.render();
(function(obj) {
obj.interval = setInterval(function() {
obj.tick();
},1000);
})(this);
return false;
} else if(this.count == 0)
return true;
else
return false;
},
render: function() {
if(this.count > 0)
this.object.innerHTML = "Download (" + this.count + " second" + (this.count == 1 ? "" : "s") + ")";
else
this.object.innerHTML = "Download Now";
}
};
window.onload = function() {
var c = new CountdownTimer("delayed",3,"http://svastara.info/.s/img/icon/download1.png");
};
<div>
<a id="delayed" class="stop" href="http://www.epiclosers.com/">Download (30sec)</a>
</div>
Have a look at the insertBefore method, the existing text should be a child node of the anchor tag.
Having said that, I'm beginning to wonder why people are doing the fancy thing here... You're not unique, I see this sort of thing all the time. The code can be simplified by allowing HTML and CSS to help you. Put the image in the document, set the display to none, and turn it on when you need it. Also, the text after download can be in a span that is also updated as you require. Then whole thing can be managed with a fraction of the code. Final thought on the simplification, you can just disable the link until you're ready to allow.
Also, using a simple debugger in the client, I can change the count to 0 on the fly and bypass the logic altogether. Or, even easier, I can just turn off javascript and click the link. In other words, make sure you're enforcing it through other means that aren't in the client. It's always a bad idea to rely on the client to enforce policy, so back it up on the server side. You may be doing that, so please don't be offended by the comment.

Jquery switching between several images on click

I'm trying to use jquery to switch between three images once you click on the image. Upon clicking on the third image, it switches it back to the first picture.
Is there a way to adapt the following to switch between more than two pictures, and for it to allow more than it switching once?
jQuery
$(document).ready(function() {
$("#clickMe").click(function() {
$("#myimage").attr({src : "picture2.png"});
});
});
HTML
<div id="clickMe"><img id="myimage" src="picture1.png" /></div>
Thanks.
This should do that:
$(document).ready(function() {
$("#clickMe").click(function() {
var src = $('#myimage').attr('src');
//if the current image is picture1.png, change it to picture2.png
if(src == 'picture1.png') {
$("#myimage").attr("src","picture2.png");
//if the current image is picture2.png, change it to picture3.png
} else if(src == "picture2.png") {
$("#myimage").attr("src","picture2.png");
//if the current image is anything else, change it back to picture1.png
} else {
$("#myimage").attr("src","picture2.png");
}
});
});
This works:
$(document).ready(function () {
var i = 1; // Used to keep track of which image we're looking at
$("#clickMe").click(function () {
i = i < 3 ? i + 1 : 1;
$("#myimage").html("picture#.png".replace("#", i));
});
});
Online demo: http://jsbin.com/afito
This is link might be helpful
http://www.sohtanaka.com/web-design/fancy-thumbnail-hover-effect-w-jquery/

Categories