I have groups of related images that I would like to be able to change (but position in the same div) by clicking on different radio buttons.
Currently I am using arrays to handle the html,
var marketingImages = [image1HTML, image2HTML, image3HTML, image4HTML];
var salaryImages = [image1HTML, image2HTML, image3HTML, image4HTML];
And when a relevant radio button is clicked, a function runs to clear the html in the div (of possible previous images), and load the new images using .append.
$(document).ready(function() {
$("#marketing, #salary").click(leed);
function leed() {
$("#portfolio-images").html("");
if ($("#marketing").is(':checked')) {
var portfolioArray = marketingImages;
} else if ($("#salary").is(':checked')) {
var portfolioArray = salaryImages;
}
for (var i=0; i<portfolioArray.length; i++) {
$("#portfolio-images").append(portfolioArray[i]);
}
...
}
It seems to work well, but being a noob though I have to wonder if there's a better way to handle this. Technically these images are just thumbnails (that can be clicked on to load larger Lightbox versions), but I'm unsure of how well that would "really" load for someone.
Does somebody know if there's a better way to handle loading groups of images? Thanks.
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'm using the Win8 Grid View Template to display infos from a news site. In the lower menu bar i have implemented a function wich shuts off the titles, so that only the pictures are still visible.
This function is in a "global.js" file which is included in the "default.html" so it's available everywhere and it looks like this:
//function to turn titles off and on
function titleToggle() {
var titles = document.getElementsByClassName("item-overlay");
for (var i = 0; i < titles.length; i++) {
if (Global.titlesAreOn) {
titles[i].style.display = "none";
}
else {
titles[i].style.display = "";
}
}
Global.titlesAreOn = !Global.titlesAreOn;
};
So when i call this function from the menu bar it works for the first items, but when i scroll the end of the groupedItems view (hubview) the titles are still there. When i then scroll back to the beginning the titles are there again too.
I'm also calling the titleToggle function from the ready() function of the "groupedItems.js" to check whether or not to display the titles depending on a global variable. When i do that (whenever i come back to the hubpage) it works all the way, just as expected.
ui.Pages.define("/pages/groupedItems/groupedItems.html", {
navigateToGroup: function (key) {
nav.navigate("/pages/groupDetail/groupDetail.html", { groupKey: key });
},
ready: function (element, options) {
appbar.winControl.disabled = false;
appbar.winControl.hideCommands(["fontSizeBt"]);
appbar.winControl.showCommands(["titleToggle"]);
if (Global.titlesAreOn == false) {
Global.titlesAreOn = true;
Global.titleToggle();
}
I made a short video to show the problem, because its kinda hard to explain --> http://youtu.be/h4FpQf1fRBY I hope you get the idea?
Why does it work when i call it from the ready() function?
Does anyone have an idea? Is it some kind of automatic item caching in order to have better performance? And how could this be solved?
Greets and thanks!
First, here is why this might be happening - WinJS is using single page navigation for the app experience. This means that when you navigate to a new page, actually you don't. Instead the content is removed from the page and the new content is loaded in the same page. It is possible that at the moment you press the button not all elements have been loaded in the DOM and therefore they cannot be manipulated by your function. This is why when you call it from the ready() function it works - all contents are loaded in the DOM. It is generally better to do things in the ready() function.
About the behavior when you slide back left and the items are again reloaded with titles - for some reason the listView items are reloading. Maybe you are using live data from the news site and they are refreshing with the listView control's template again. I cannot know, but it doesn't matter. Hiding the elements is not the best approach I think. It is better to have two templates - one with a title element and one without. The button click handler should get the listView controls(they have to be loaded) and change their templates.
ready: function (element, options) {
var button = document.getElementById('btn');
button.addEventListener("click", btnClickHandler);
}
And the handler:
function btnClickHandler(e) {
var listView = document.getElementById("listView").winControl;
var template2 = document.getElementById("template2");
listView.itemTemplate = template2;
};
Quite a simple question, yet it has been bugging me all week!
Firstly, I do not expect someone to write me this huge piece of code, then me take it away and claim it for my own. Would prefer someone to actually help me write this :)
I am attempting to show a playlist on my website as a png image.
I have 2 playlists that must be shown.
The playlist will change on an image press.
I have 4 button images, 'CD1up', 'CD1down', 'CD2up' and 'CD2down'.
I would like to have these buttons changing what current playlist is being shown, but also showing the buttons correct state. For example, is playlist1 is being shown, then 'CD1up' must be shown, and 'CD2down' shown.
I would post my current code here, but I basically scrapped it all and decided to start from scratch since I'm terrible with web javascript.
All help is greatly appreciated!
I can basically fluent in HTML and CSS, but horrible at web javascript.
Some notes:
If you give each image an id attribute, you can use document.getElementById to get a reference to that element once the page is loaded.
Then you can set the src property on that element to a new URL to change the image.
Make sure your script tag is after the elements in the HTML (just before the closing </body> works) so that the elements exist when you want them.
You can add a click event handler to any element on the page. Most browsers support addEventListener but some older versions of IE still require you to use attachEvent to hook up the handler. So you see people with functions that look something like this:
function hookEvent(element, eventName, handler) {
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
}
else if (element.attachEvent) {
element.attachEvent("on" + eventName, handler);
}
else {
element["on" + eventName] = function(event) {
return handler.call(this, event || window.event);
};
}
}
So for example, if you have this img:
<img id="myImage" src="/path/to/img.png">
This cycles through four images on click:
<!-- This must be AFTER the `img` above in the HTML,
just before your closing /body tag is good -->
<script>
(function() {
var myImage = document.getElementById("myImage"),
images = [
"/path/to/img1.png",
"/path/to/img2.png",
"/path/to/img3.png",
"/path/to/img4.png"
],
index = -1;
hookEvent(myImage, "click", imageClick);
function imageClick() {
++index;
if (index >= images.length) {
index = 0;
}
myImage.src = images[index];
}
})();
</script>
You can get a lot of utility functionality and smooth over browser differences using a decent library like jQuery, YUI, Closure, or any of several others, although if all you want to do on the page is change the images sometimes and handle a click or two, that might be overkill.
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 have run into numerous sites that use a delay in loading images one after the other and am wondering how to do the same.
So i have a portfolio page with a number of images 3 rows of 4, what i want to happen is for the page to load,except for the images in img tags. Once the page has loaded i want images 1 of each row to load then say 0.5 seconds later the next image in the row(s) and so no. I'm going to have a loading gif in each image box prior to the actual image being displayed.
I know its doable but cant seem to find the term for doing this. This is purely for looks as it is a design site.
Thanks for the help.
This is very easy to do in jQuery
$('img').each(function(i) {
$(this).delay((i + 1) * 500).fadeIn();
});
Fiddle: http://jsfiddle.net/garreh/Svs7p/3
For fading in rows one after the other in a table it just means changing the selector slightly. Remember to change from div to img -- I just used div for testing
$('tr').each(function(i) {
$('td div', this).delay((i + 1) * 500).fadeIn();
});
Fiddle: http://jsfiddle.net/garreh/2Fg8S/
Here is what you can do, you can load the image tags with out the src and using a custom property:
<img alt='The image' path='image/path.jpg' />
then you can use javascript to load the images when the site is loaded or whenever you please;
// simplified
window.onload = function () {
var images = document.getElementsByTagName('img');
// loop and assign the correct
for (var i =0; i < images.length;i++){
var path = images[i].getAttribute('path');
images[i].src = path;
}
}
I hope you get the concept of how the images are delayed
**please note the path attribute is not a standard one.
The easiest way I can think to do this is to have a table set up that will eventually hold the image tags, but have none on load. Javascript can loop through an array of image urls, and insert those image tags into random locations on the table.
If you want to have the delay, setInterval is the perfect tool. http://www.w3schools.com/jsref/met_win_setinterval.asp
// You can hard-code your image url's here, or better still, write
// a server-side script that will read a directory and return them
// so it is fully dynamic and you can add images without changing code
unpickedImages = array();
// Start loading
loadAllImages = setInterval( insertImage, 600 );
function insertImage() {
if( unpickedImages.length > 0 ) {
var imageUrl = unpickedImages.shift();
// pick empty x, y on your table
// Insert the image tag im that <td></td>
} else {
clearInterval( loadAllImages );
}
}
You really don't need javascript to do this. If you specify the image sizes in the HTML or CSS, the browser will layout and display the page while loading the images, which will likely be loaded in parallel. It will then display them as soon as it can.
That way if users re-visit your site and have the images cached, they all show up immediately. If you have a script to load the images after a delay, you are making visitors wait for content unnecessarily and all their efforts to have a faster browser and pay for a fast internet connection has gone to waste.