Image won't be resized in javascript when removing alerts - javascript

I have a database with image paths. through PHP, I insert the pictures on my website. The problem is that the code that I have won't work. So, I decided to put some alerts to figure out what is the issue. After going through the alerts, I noticed that the images were resized and repositioned. After some reading, I found out that this is because the javascript is executed in the same time as the HTML and CSS and the alert halts the javascript, letting the HTML and CSS to be executed. How should I change my code to make the images work? This is the code in question:
var box = document.getElementsByClassName("produs");
var pic = document.getElementsByClassName("imagine_produs");
var i;
for (i = 0; i < pic.length; i++) {
alert(pic[i].width);
if ( pic[i].width > 200 ) {
pic[i].width="200";
alert(pic[i].width);
}
var marg = (box[i].clientWidth - pic[i].clientWidth ) / 2;
pic[i].style.marginLeft = marg + "px";
pic[i].style.marginRight = marg + "px";
}
Also, I have made a photo album that is in order to show how the code executes:
What other way is there to either halt the code or to rearrange it so that it works like in the last picture?
THanks!

You might use
console.log()
instead of alert() for debugging purposes. That way you can monitor what your code is doing without interrupting it with prompts.
Apart from that, the funtionality of your code might better be realised with CSS eventually (i.e. margin:auto; img max-width:90%; …).

Related

Reloading a DIV's image and class by Javascript on click of separate DIV.

The code I’m working with is too long to post, so I’ve made a fiddle here: http://jsfiddle.net/Emily92/5b72k225/
This code takes a random image and cuts it up into a number of pieces depending on the class that is applied in the div which contains the image.
When the page loads, a random image is selected from the array and the class is applied to it, what I’m trying to do is create a separate div, which when clicked on will reload the div containing the image. The result I’m looking for is for the image to be replaced by a new random image with the class applied to it.
Right now, the only way I can make a new image appear in the div is to reload the entire page, ideally this would be achieved by just having the div reload instead of all the other page elements reloading too.
I haven’t been able to do this so far but have received some help on here on how to reload an image and class on click of a div, lines 980-1018 of the Javascript code in the jsfiddle is the current attempt at achieving this, but solving this problem seems much more complicated as the image is being manipulated by the Javascript code, so perhaps this needs to also be reloaded at the same time as the new randomised image is selected?
This is the current attempt at solving this problem:
$(function() {
var imageArray = [
'http://www.webdesignhot.com/wp-content/uploads/2009/10/CatsVectorImage.jpg',
'http://www.costume-works.com/images/halloween_cat_in_witch_hat.jpg',
'http://onthewight.com/wp-content/2013/04/sooty-ryde.jpg'];
reloadImages(imageArray);
$('#reload').on('click',function(){
$( "#masterdiv img[id^='div']" ).each(function(index){
$(this).removeClass("jqPuzzle jqp-r"+(index+3)+"-c"+(index+3)+"-SCN");
$(this).fadeOut( "slow", function() {
if(index==0) {
reloadImages(imageArray);
}
$(this).addClass("jqPuzzle jqp-r"+(index+3)+"-c"+(index+3)+"-SCN");
$(this).fadeIn();
});
});
});
});
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function reloadImages(array){
shuffleArray(array);
for(var i=0;i<3;i++){
// places the first image into all divs
document.getElementById('div'+(i+1)+'id').src=array[0];
}
}
I’ve written more details on the issue in the html section of the jsfiddle. I'd really appreciate any advice in solving this and thank you for any help in advance!
The plugin reads the images' src before page load, takes them and then generates the puzzle. As such, you can not just update the images as they're not there anymore. So you'd have to clear the divs under each difficulty classes (easyDiv,mediumDiv,hardDiv), append a new <img> under each div then calls / reload the plugin. Updated code in : http://jsfiddle.net/5b72k225/6/
Changes I've made:
Separate old reloadImages into initImages and reloadImages. initImages is called in the beginning, while reloadImages is called when reloading.
Created new function makePuzzle by taking out the intialization of the plugin from $(document).ready() block, so makePuzzle can be called after reloading new image.
The new $(document).ready() block now initializes the images and attaches click event handler to the button. When clicked, divs are emptied, new <img>s inserted and plugin is called.

How to properly scroll IFrame to bottom in javascript

For a mockup-webpage used for research on interaction on websites, I created a mockup message-stream using JavaScript. This message stream is loaded in an IFrame and should show images at pre-set intervals and scroll to the bottom of the page after placing a new image at the bottom of the page. Getting the images to appear is working quite well with the provided script. However, both Chrome and IE seem to have trouble scrolling the page to the bottom. I would like to scroll to the bottom of the page as soon as the image is attached, but have for now added a 5 ms delay because that seemed to work sometimes. My questions are:
Is it okay to use document.body.scrollHeight for this purpose?
Can I make the scroll occur directly, or do I need a small interval before scrolling?
How to make the code scroll to the bottom of the IFrame directly after adding an image?
The following functions are used and trypost() is started onLoad:
function scrollToBottom(){
window.scrollBy(0,document.body.scrollHeight);
}
function trypost(){
point = point + 1;
if(point < interval.length){
//create and append a new image
var newImg = document.createElement("IMG");
newImg.src = "images/"+images[point]+".png";
document.getElementById('holder').appendChild(newImg);
//create and append a return
var br = document.createElement("br");
document.getElementById('holder').appendChild(br);
//time scroll to bottom (after an arbitrary 5 seconds)
var stb = window.setTimeout(scrollToBottom, 5);
//time next post
var nextupdate = interval[point]*400;
var tp = window.setTimeout(trypost, nextupdate);
}
}
My script section contains at least the following variables:
var point = -1;
var interval = [10, 10, 15];
var images = ["r1", "a1", "r2"];
This questions is a continuation of the project described in How to proper use setTimeout with IE?
To answer one of your questions, document.body.scrollHeight is appropriate for this purpose, but not if you're actually calling for document. That'll give you the scroll height of the document the iFrame is in, not the iFrame's document. The iFrame's document can be called upon by [insert variable for iFrame here].contentDocument.
Here's how I did it (and by that, I mean I tested it out with my own stuff to make sure it worked):
let i = document.querySelector('iframe')
i.contentWindow.scrollTo(0, i.contentDocument.body.scrollHeight);
That being said, the other answer by Thomas Urban will also work most of the time. The difference is only if your page has a really long scroll height. Most pages won't be longer than 999999 (for all I know that's impossible and that's why they chose that number), but if you have a page longer than that, the method I showed here would scroll to the bottom and the 999999 would scroll to somewhere not yet at the bottom.
Also note, if you have more than one iFrame, you're gonna want to query it in a different way than I did, like by ID.
Scrolling to bottom is always like scrolling to some ridiculously large top offset, e.g. 999999.
iframe.contentWindow.scrollTo( 0, 999999 );
In addition see this post: Scrolling an iframe with javascript?
If scrolling occurs too early it's probably due to images not being loaded yet. Thus, you will have to scroll as soon as added image has been loaded rather than on having placed it. Add
newImg.onload = function() { triggerScrolling(); };
after creating newImg, but before assigning property src.
If several events are required to trigger scrolling you might need to use some "event collector".
function getEventCollector( start, trigger ) {
return function() {
if ( --start == 0 ) { trigger(); )
};
}
You can then use it like this:
var collector = getEventCollector( 2, function() { triggerScrolling(); } );
newImg.onload = collector;
window.setTimeout( collector, 100 );
This way triggerScrolling() is invoked after 100ms at least and after image has been loaded for collector has to be invoked twice for triggerScrolling() being invoked eventually.

jQuery Image load error not being called after page load

Hello Stack Overflow community, recently, I've been working on a quick image display using jQuery. It has a list of possible images that can be picked and displayed at random. The issue is, after the page has finished loading, jQuery ceases to detect image load errors for if the image is invalid.
My current method of finding and fixing errors is as follows:
$('img').error(function() {
$(this).attr('src',getImgUrl());
});
This, in normal circumstances such as the page being loaded, picks a valid image, even if multiple invalid images are specified in a row. However, after the page is finished loading, if an invalid image is picked, and fails to load, this function is not even called. Strangely enough though, if I add an onerror attribute to all images, they are always called from the onerror no matter if the page was freshly loaded or not, so why is jQuery having this issue? Any help is appreciated, thanks.
UPDATE:
It also appears this is happening to other jQuery functions as well, such as click.
UPDATE:
It would appear to be an issue with jQuery recognizing new elements on a page, such as newly created images.
UPDATE for those asking getImageUrl:
function getImgUrl()
{
var text = (Math.round(Math.random() * 3)).toString();
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0; i < 4; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return '/' + text;
}
All this does is pick a random URL, which matches occasionally to an image on my web-server that has many many images.
It would appear that jQuery has issues recognizing new elements on the page, so the way I fixed this was instead of deleting and adding images to the page, I just edited the existing SRC of images when doing changes, which strangely enough, the jQuery error function responds perfectly to.
Here's the refresh function I ended up coming up with for all interested:
function refreshImages()
{
var images = 10;
for(var i = 0;i < images;i++)
{
var url = getImgUrl();
$('#thumb' + i).attr('src',url);
if(i == 0)
{
$('#fullimage').attr('src',url);
$('.thumb').css('border','2px solid white');
}
}
resize();
}

Fade in an HTML element with raw javascript over 500 miliseconds

Once again I find myself stuck by something that I just don't understand. Any help would be appreciated.
I'm working on a modal window, you click something and the background is masked and a modal window shows some content.
I have a div with "display:none" and "opacity:0", and when the user triggers the modal, this div will overlay everything and have certain transparency to it.
In my mind, what I need to do is:
Set the opacity
Perform a "for" loop that will check if the opacity is less than the desired value.
Inside this loop, perform a "setInterval" to gradually increment the value of the opacity until it reaches the desired value.
When the desired value has been reached, perform an "if" statement to "clearInterval".
My code so far is as follows:
var showMask = document.getElementById('mask');
function fireModal(){
showMask.style.opacity = 0;
showMask.style.display = 'block';
var getCurrentOpacity = showMask.style.opacity;
var increaseOpacity = 0.02;
var finalOpacity = 0.7;
var intervalIncrement = 20;
var timeLapse = 500;
function fadeIn(){
for(var i = getCurrentOpacity; i < finalOpacity; i++){
setInterval(function(){
showMask.style.opacity = i;
}, intervalIncrement)
}
if(getCurrentOpacity == finalOpacity){
clearInterval();
}
}
fadeIn();
}
As you all can guess, this is not working, all it does is set the opacity to "1" without gradually fade it in.
Thanks in advance for your help.
You should use jquery, mootools or extjs for something like this.
But basically you need to do this:
var id = setInterval(function() {
showMask.style.opacity += .05;
if (showMask.style.opacity >= 1)
{
clearInterval(id);
}
},200)
This will fade in over 2 seconds.
Rack my up as another who strongly advises using jQuery. In my work environment I often face similar challenges due to corporate bosses who are basically afraid of any and all advancement, so I understand your predicament. But, that being said, my suggestion is instead of spending time re-writing the wheel, spend time figuring out how to use the proper solution, which is, in this case jQuery or other javascript framework. If you can write your own function, you can use jQuery.
<script>
document.write("<scr" + "ipt src='http://givemejquery'></scr" + "ipt>");
</script>

Javascript Show and Hide Divs Reloads Complete Page in IE6

and thank you for taking a look at this question.
We have developed a website which has a navigation control (Next and Previous buttons) written in Flash. These buttons use ExternalInterface to call a Javascript function in my webpage, e.g. ExternalInterface.call("showPage", pageNum);
My HTML page contains a number of Divs which each represent a single 'screen'. The first Div (screen) has the CSS Display set to 'inline' and all of the remaining are set to 'none'.
The Javascript showPage function which is called when the Flash button is clicked is as follows and it calls the hideShow function:
function showPage(which) {
if (pagetype == "lo"){
if(which < 0 && isRunningInFrame()){goPrev();}
else if (which > maxPageNum && isRunningInFrame()){goNext();}
else{dsPages.setCurrentRow(which);}
}
hideShow('page' + currentRow, 'page' + which);
prevRow = currentRow;
currentRow = which;
}
function hideShow(hideDiv, showDiv){
if(document.getElementById(hideDiv)!=null){
document.getElementById(hideDiv).className = "hideDiv clear";
}
if(document.getElementById(showDiv)!=null){
document.getElementById(showDiv).className = "showDiv clear";
}
}
This all works well in contemporary browsers and is very responsive. However our client has Internet Explorer 6 on all of their PCs (well they would wouldn't they!) and when you click Next the complete page reloads. I only assume this is happening because I can see in the bottom left corner of the browser (in the grey bar) all of the JPEG images loading. Some of the HTML pages contain approximately 50 'screens' and this is very slow when they all load over and over again.
I would be very grateful if anyone can see why this is happening or could suggest a more efficient approach to this.
Thank you.
Regards
Chris
Pointy may have a point here (no pun intended). A simple guess-suggestion would be to try placing a 'return false;' after your js-call.

Categories

Resources