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
Related
I'm responsible for developing an approach/algorithm to hide image on the trigger. But hiding should be in such a way that it would be hard for developers to do "inspect code" and change certain javascript variables or setting some condition true. So visibility:hidden is a no for sure because it's easy to get rid of it through "inspect code".
Only viable option I can think of is injecting image code () through JQuery which would make it quite work for someone to trigger it manually (I believe). But not sure if it's good enough.
What kind of an approach I can implement? Every opinion counts. Thank you.
To clarify: there are 2 images. each button hover will trigger visibility of one of the images. And the goal is to forbid the user from viewing both of them simultaneously. And they may avoid this by changing script conditions and variables. How to prevent that happening?
You could use something like the below to detect when someone uses inspect element to completely hide the content they're trying to change.
var currentHtmlContent;
var element = new Image();
var elementWithHiddenContent = document.querySelector("#element-to-hide");
var innerHtml = elementWithHiddenContent.innerHTML;
element.__defineGetter__("id", function() {
currentHtmlContent= "";
});
setInterval(function() {
currentHtmlContent= innerHtml;
console.log(element);
console.clear();
elementWithHiddenContent.innerHTML = currentHtmlContent;
}, 1000);
It will then show the content when they stop inspecting.
I have a slightly vague question. I have the following in my code: http://jsfiddle.net/PMnmw/2/
In the jsfiddle example, it runs smoothly. The images are swapped quickly and without any hassle. When it is in my codebase though, there is a definite lag.
I'm trying to figure out why that lag is happening. The structure of the jquery is exactly the same as above. I.e. Inside the $(document).ready (...) function, I have a check to see if the user clicked on the img (based on the classname) and then I execute the same code as in the jsfiddle.
I'm at my wits end trying to figure out what to do here... Clearly I'm not doing the swap right, or I'm being very heavy handed in doing it. Prior to this, one of my colleagues was using AJAX to do the swap, but that seems to be even more heavy duty (a full fledged get request to get the other icon...).
I've modified your fiddle: http://jsfiddle.net/PMnmw/12/
Things I've optimized:
Created a variable for both img1 and img2, so that you won't have to navigate the DOM to reference those two images anymore, thusly improving performance.
Applied a click handler to the images themselves, so you don't have to search the children of the wrapper.
The basic idea was to reduce the number of jquery selections as much as possible.
Let me know if this helped speed things up.
$(document).ready(function() {
var img1 = $('#img1');
var img2 = $('#img2');
$(".toggle_img").click(function(e) {
var target = $(e.target);
if(target.is(img1)){
img1.hide();
img2.show();
}
else if (target.is(img2)) {
img2.hide();
img1.show();
}
});
});
Images that are not visible are normally not loaded by the browser before they are made visible. If there seems to be a problem, start by downloading an image optimizer like RIOT or pngCrush to optimize your images.
If it's only two arrows, you should consider joining them into a CSS sprite.
You could try not doing everything with jQuery, but it shouldn't really make that much difference.
Something like this maybe, with the hidden image loaded in JS and some traversing done outside jQuery (but that is probably not the problem, although the code seems overly long for a simple image swap?) :
$(document).ready(function() {
var img=new Image();
img.src='http://i.imgur.com/ZFSRC.png'; //hidden image url
$(".wrapper").click(function(e) {
if(e.target.className=='toggle_img') {
$('.toggle_img').toggle();
if (e.target.parentNode.childNodes[1].style.display=='none') {
console.log("hello");
} else {
console.log("goodbye");
}
}
});
});
FIDDLE
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 ?
I have seen a lot of websites which "wrapper" width is 960px. As a background image they have an image which is clickable (some kind of advertise) and the whole webpage is over that image, like on this site.
Can you give me tutorial or something on that ?
Tom's code was a huge help, but I needed pointer cursor for this type of ad, but not for all the site, so I came up with this solution:
$('body').bind('click', function(e) {
if ($(e.target).closest('#container').size() == 0) {
alert('click');
}
}).bind('mouseover', function(e) {
if ($(e.target).closest('#container').size() == 0) {
$(this).css('cursor','pointer');
} else {
$(this).css('cursor','default');
}
});
In the first place you put the ad image as the website background then basically you have to capture the click on the whole body and check if it was in-or-outside of the page content. To do that you have to check if the event target element have the content wrapper (or wrappers if there are multiple) as one of its parent nodes - if not it means the click was outside of the page content.
If you'd like to do it here on StackOverflow you could do it with this bit of code.
$('body').bind('click', function(e){
if(!$(e.target).closest('#content').length) {
alert('ad outside content clicked');
}
});
Feel free to try it in your javascript console - SO is using jQuery so it will work - when you will click outside of the content area (at the edges of the screen) you will get alert that ad was clicked.
You'd obviously have to replace the alert with any kind of callback you'd have for your commercial - opening a new web page or whatever
Hope that helps
Tom
ps.
Keep in mind that this example is using jQuery for simplicity not native JS so you'd need the library for it to work.
I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.
What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this.
I've been doing this via JavaScript, which works so far, using the following code
document.getElementById('chart').src = '/charts/10.png';
The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond.
What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it.
I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image.
A good suggestion I've had is to use the following
<img src="/charts/10.png" lowsrc="/spinner.gif"/>
Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed.
Any other ideas?
I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback.
function PreloadImage(imgSrc, callback){
var objImagePreloader = new Image();
objImagePreloader.src = imgSrc;
if(objImagePreloader.complete){
callback();
objImagePreloader.onload=function(){};
}
else{
objImagePreloader.onload = function() {
callback();
// clear onLoad, IE behaves irratically with animated gifs otherwise
objImagePreloader.onload=function(){};
}
}
}
You could show a static image that gives the optical illusion of a spinny-wheel, like these.
Using the load() method of jQuery, it is easily possible to do something as soon as an image is loaded:
$('img.example').load(function() {
$('#spinner').fadeOut();
});
See: http://api.jquery.com/load-event/
Use the power of the setTimeout() function (More info) - this allows you set a timer to trigger a function call in the future, and calling it won't block execution of the current / other functions (async.).
Position a div containing the spinner above the chart image, with it's css display attribute set to none:
<div> <img src="spinner.gif" id="spinnerImg" style="display: none;" /></div>
The nbsp stop the div collapsing when the spinner is hidden. Without it, when you toggle display of the spinner, your layout will "twitch"
function chartOnClick() {
//How long to show the spinner for in ms (eg 3 seconds)
var spinnerShowTime = 3000
//Show the spinner
document.getElementById('spinnerImg').style.display = "";
//Change the chart src
document.getElementById('chart').src = '/charts/10.png';
//Set the timeout on the spinner
setTimeout("hideSpinner()", spinnerShowTime);
}
function hideSpinner() {
document.getElementById('spinnerImg').style.display = "none";
}
Use CSS to set the loading animation as a centered background-image for the image's container.
Then when loading the new large image, first set the src to a preloaded transparent 1 pixel gif.
e.g.
document.getElementById('mainimg').src = '/images/1pix.gif';
document.getElementById('mainimg').src = '/images/large_image.jpg';
While the large_image.jpg is loading, the background will show through the 1pix transparent gif.
Building on Ed's answer, I would prefer to see something like:
function PreLoadImage( srcURL, callback, errorCallback ) {
var thePic = new Image();
thePic.onload = function() {
callback();
thePic.onload = function(){};
}
thePic.onerror = function() {
errorCallback();
}
thePic.src = srcURL;
}
Your callback can display the image in its proper place and dispose/hide of a spinner, and the errorCallback prevents your page from "beachballing". All event driven, no timers or polling, plus you don't have to add the additional if statements to check if the image completed loading while you where setting up your events - since they're set up beforehand they'll trigger regardless of how quickly the images loads.
Some time ago I have written a jQuery plugin which handles displaying a spinner automatically http://denysonique.github.com/imgPreload/
Looking in to its source code should help you with detecting when to display the spinner and with displaying it in the centre of the loaded image.
I like #duddle's jquery method but find that load() isn't always called (such as when the image is retrieved from cache in IE). I use this version instead:
$('img.example').one('load', function() {
$('#spinner').remove();
}).each(function() {
if(this.complete) {
$(this).trigger('load');
}
});
This calls load at most one time and immediately if it's already completed loading.
put the spinner in a div the same size as the chart, you know the height and width so you can use relative positioning to center it correctly.
Aside from the lowsrc option, I've also used a background-image on the img's container.
Be aware that the callback function is also called if the image src doesn't exist (http 404 error). To avoid this you can check the width of the image, like:
if(this.width == 0) return false;
#iAn's solution looks good to me. The only thing I'd change is instead of using setTimeout, I'd try and hook into the images 'Load' event. This way, if the image takes longer than 3 seconds to download, you'll still get the spinner.
On the other hand, if it takes less time to download, you'll get the spinner for less than 3 seconds.
I would add some random digits to avoid the browser cache.