my script only working from console - javascript

I have a script that I put inside my html doc.
when I load the html page the script is not working,but when I put the script inside the console then the script is working an making the effect I want on the html doc.
here is the script,what i'm doing wrong?
var maxRows = 10;
$('.table').each(function() {
var cTable = $(this);
var cRows = cTable.find('tr:gt(0)');
var cRowCount = cRows.size();
if (cRowCount < maxRows) {
return;
}
cRows.each(function(i) {
$(this).find('td:first').text(function(j, val) {
return (i + 1) + " - " + val;
});
});
cRows.filter(':gt(' + (maxRows - 1) + ')').hide();
var cPrev = cTable.siblings('.prev');
var cNext = cTable.siblings('.next');
cPrev.addClass('disabled');
cPrev.click(function() {
var cFirstVisible = cRows.index(cRows.filter(':visible'));
if (cPrev.hasClass('disabled')) {
return false;
}
cRows.hide();
if (cFirstVisible - maxRows - 1 > 0) {
cRows.filter(':lt(' + cFirstVisible + '):gt(' + (cFirstVisible - maxRows - 1) + ')').show();
} else {
cRows.filter(':lt(' + cFirstVisible + ')').show();
}
if (cFirstVisible - maxRows <= 0) {
cPrev.addClass('disabled');
}
cNext.removeClass('disabled');
return false;
});
cNext.click(function() {
var cFirstVisible = cRows.index(cRows.filter(':visible'));
if (cNext.hasClass('disabled')) {
return false;
}
cRows.hide();
cRows.filter(':lt(' + (cFirstVisible +2 * maxRows) + '):gt(' + (cFirstVisible + maxRows - 1) + ')').show();
if (cFirstVisible + 2 * maxRows >= cRows.size()) {
cNext.addClass('disabled');
}
cPrev.removeClass('disabled');
return false;
});
});

You're most likely running that script before the elements that it references exist.
Make sure that the <script> tag comes later in the page than the element with the class table or wrap your entire script in:
$(function(){
... Your entire script
});
in order to ensure that it does not execute until the DOM is ready.

Try wrapping the whole thing with this:
$(document).ready(function () { /* existing code */ });
The browser may be executing your code before the page has loaded and therefore before the elements exist.

A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$( document ).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute. Code included
inside $( window ).load(function() { ... }) will run once the entire
page (images or iframes), not just the DOM, is ready.
Try wrapping your code in this
$(document).ready(function() {
// Your code here
});
The Source

Related

My script needs page refresh for it to run

Every time I load my page for the first time my script does not load, I need to refresh the page at least 3 times for it to run. How can I make my script run without a page refresh? This particular script is in BABEL.
'use strict';
var deg = 0;
var index = 0;
$('#' + index).css('opacity', '1');
$('.navbar').contextmenu(function () {
return false;
});
$('.navbar').on('mousewheel', function (e) {
var move = -60;
var nextIndex = nextIndex = (index + 1) % 6;
if (e.originalEvent.wheelDelta / 120 <= 0) {
// wheel up
move = 60;
nextIndex = index -1 < 0 ? 5 : index - 1;
}
$('.scroll-list').css('transform', 'rotateX(' + (deg + move) + 'deg)');
$('#' + index).css('opacity', '0.01');
$('#' + nextIndex).css('opacity', '1');
index = nextIndex;
deg = deg + move;
event.stopPropagation();
console.timeEnd('cache');
});
And what if you wrapped your code inside a window.onload function?
window.onload = function() {
// your code
}
Your code will only run when the html document is "ready" and fully loaded.
You are running Javascript that depends on page elements and the javascript is executed before the elements are on the page;
Wrapp all your code inside document.ready function
$(document).ready(function () {
var deg = 0;
var index = 0;
$('#' + index).css('opacity', '1');
$('.navbar').contextmenu(function () {
return false;
});
$('.navbar').on('mousewheel', function (e) {
var move = -60;
var nextIndex = nextIndex = (index + 1) % 6;
if (e.originalEvent.wheelDelta / 120 <= 0) {
// wheel up
move = 60;
nextIndex = index - 1 < 0 ? 5 : index - 1;
}
$('.scroll-list').css('transform', 'rotateX(' + (deg + move) + 'deg)');
$('#' + index).css('opacity', '0.01');
$('#' + nextIndex).css('opacity', '1');
index = nextIndex;
deg = deg + move;
event.stopPropagation();
console.timeEnd('cache');
});
});
Wrap your code in ready function, so that your JavaScript executes after DOM is loaded.

If Statement not registering in JavaScript

I can't figure out why these if statements aren't working. I have tried setting the second one to else if as well and it's still not working.
Basically I want to the code to add 1 to the count variable whenever a button is pressed. The problem is that even though the count++ is working, the if statements aren't registering and I can just keep playing around in the if (count== 0) section.
var player = "X";
var comp = "O";
var count = 0;
console.log(count);
//Code for turn 1
if (count == 0) {
//Code for Div 1
$("#1").one("click", function(){
console.log("hit")
count++;
console.log(count)
if ( $('#1').children().length == 0 ){
$("#1").append("<p>" + player + "</p>");
$("#5").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
});
//Code for Div 2
$("#2").one("click", function(){
console.log("hit")
count++;
console.log(count);
if ( $('#2').children().length == 0 ){
$("#2").append("<p>" + player + "</p>");
$("#5").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
});
if (count == 1){
$("#2").one("click", function(){
count++;
if ( $('#2').children().length == 0 ){
$("#2").append("<p>" + player + "</p>");
$("#3").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
})
console.log(count);};
Any logic that needs to be executed on each click must be triggered by that click. Right now, the ifs at the top level are only run once, not in response to clicks.
You're using $("#1").one, which by definition only works once:
Description: Attach a handler to an event for the elements. The
handler is executed at most once per element per event type. (source)
Change all .one's to .on.

Putting simple functions that contain jquery in a jquery execution queue

I have a number of functions containing jquery that should be executed sequentially. They aren't used to create effects but rather to position certain elements at a calculated location inside a div. All online resources on jquery queue are focused on the creation of transitions or animations so it's hard to find a simple example on how to execute a number of simple functions sequentially.
I have these functions:
function bigItemRecalc(recalc, idBase, innerHeight, i) {
if (recalc < 0) {
$('#' + idBase + i).css('max-height', (innerHeight + (2 * recalc)));
recalc = 0;
}
return recalc;
}
function firstCheck(recalc, idBase, i) {
if (i == 1) {
$('#' + idBase + i).css('margin-top', recalc * -1);
}
}
function lastCheck(recalc, idBase, itemAmount, i) {
if (i == itemAmount) {
$('#' + idBase + i).css('margin-top', recalc);
}
}
function truncateItems(totalHeight, widgetHeight, idBase, i) {
if (totalHeight > (widgetHeight - 20)) {
$('#' + idBase + i).remove();
$('#' + idBase + "b" + i).remove();
}
}
In another function I want to execute these sequentially by using a jquery queue preferably , but I haven't got a clue how.
The code is called here:
function styleWidget(itemAmount, widgetHeight, widgetWidth, idBase) {
var innerHeight;
var outerHeight;
var recalc;
var totalHeight = 0;
var totalWidth = 0;
for (var i = 1; i <= itemAmount; i++)
{
if (widgetHeight >= widgetWidth)
{
totalHeight += $('#'+idBase+i).height();
innerHeight = $('#' + idBase + i).height();
outerHeight = (widgetHeight/itemAmount);
recalc = ((outerHeight / 2) - (innerHeight / 2));
recalc = bigItemRecalc(recalc, idBase, innerHeight, i);
$('#' + idBase + i).css('padding-top', recalc);
firstCheck(recalc, idBase, i);
lastCheck(recalc, idBase, itemAmount, i);
truncateItems(totalHeight, widgetHeight, idBase, i);
}
else
{
innerHeight = $('#'+idBase+i).height();
outerHeight = widgetHeight;
recalc = ((outerHeight/2)-(innerHeight/2));
$('#'+idBase+i).css('padding-top',recalc);
totalWidth += $('#'+idBase+i).width();
if (totalWidth > (widgetWidth-20))
{
$('#' + idBase + i).remove();
$('#' + idBase + "b" + i).remove();
}
}
}
}
The bottom part hasn't been updated just yet, but it can be ignored as it's being tested with portrait mode widgets.
I think I've found a clue. When no delay is introduced the values of totalHeight and innerHeight seem very low. So I assume that the page isn't fully loaded by the time the script is executed. Every time a new widget is generated the above script is called like this:
$(document).ready(styleWidget(3, 225, 169, 'id-871206010'));
This fixed it:Why does Firefox 5 ignore document.ready?
It seems like reloading the page did not trigger the .ready() function.

function doesn't execute on jquery document ready

I have a javascript function that resize and centers images based on the surrounding container size (that in turn depend on the window size). I use jquery as js framework. The function need to be executed after document load (on document ready) but also when and if the user changes size of the browser, ie I have the following running in the html-document:
$(document).ready(function(){
fixImageSizes();
});
$(window).resize(function() {
fixImageSizes();
});
But for some unknown reason the function is only executed when a user resizes the browser and not after loading. Can anyone please help with this?
(my function is below for knowledge...)
function fixImageSizes()
{
var cw = $('#imagecontainer').width();
var ch = $('#imagecontainer').height();
$('#imagecontainer img').each(function()
{
var iw = $(this).css('width');
var ih = $(this).css('height');
if (parseInt(iw) < parseInt(cw)) // image width < viewport
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) < parseInt(ch)) // image height < viewport
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
if (parseInt(ih) > parseInt(ch) && parseInt(iw) > parseInt(cw)) // viewport smaller than image, shrink image
{
if (parseInt(ch) - parseInt(ih) > parseInt(cw) - parseInt(iw)) // difference is less on height
{
var newiw = Math.ceil(parseInt(iw) * parseInt(ch) / parseInt(ih)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(ch)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(newiw)/2) + 'px';
$(this).css({'width':newiw,'height':ch,'margin-left':newimarginl,'margin-top':newimargint});
}
else // difference less on width
{
var newih = Math.ceil(parseInt(ih) * parseInt(cw) / parseInt(iw)) + 'px';
var newimargint = '-' + Math.ceil(parseInt(newih)/2) + 'px';
var newimarginl = '-' + Math.ceil(parseInt(cw)/2) + 'px';
$(this).css({'width':cw,'height':newih,'margin-left':newimarginl,'margin-top':newimargint});
}
}
});
You should use the load event instead of the ready event.
The ready event runs after the document has loaded, but before the images has loaded, so you won't have the correct size of all elements.
The function is probably executing (you can double-check with a simple alert), but the images you are "fixing" is probably not loaded yet. You can use the window.onload event or listen to the image load event like this:
var scale = function() {
// rescale
};
$('#imagecontainer img').each(function() {
this.complete ? scale.call(this) : $(this).load(scale);
});
Try this:
$(window).load(function (){
fixImageSizes();
});

Getting Javascript/jQuery scrolling function to work on successive divs

I'm currently trying to implement functionality similar to infinite/continuous/bottomless scrolling, but am coming up with my own approach (as an intern, my boss wants to see what I can come up with on my own). So far, I have divs of a fixed size that populate the page, and as the user scrolls, each div will be populated with an image. As of now, the function I've written works on the first div, but no longer works on successive divs.
$(window).scroll(function () {
var windowOffset = $(this).scrollTop();
var windowHeight = $(this).height();
var totalHeight = $(document).height();
var bottomOffset = $(window).scrollTop() + $(window).height();
var contentLoadTriggered = new Boolean();
var nextImageCount = parseInt($("#nextImageCount").attr("value"));
var totalCount = #ViewBag.totalCount;
var loadedPageIndex = parseInt($("#loadedPageIndex").attr("value"));
var calcScroll = totalHeight - windowOffset - windowHeight;
$("#message").html(calcScroll);
contentLoadTriggered = false;
if (bottomOffset >= ($(".patentPageNew[id='" + loadedPageIndex + "']").offset().top - 1000)
&& bottomOffset <= $(".patentPageNew[id='" + loadedPageIndex + "']").offset().top && contentLoadTriggered == false
&& loadedPageIndex == $(".patentPageNew").attr("id"))
{
contentLoadTriggered = true;
$("#message").html("Loading new images");
loadImages(loadedPageIndex, nextImageCount);
}
});
This is the image-loading function:
function loadImages(loadedPageIndex, nextImageCount) {
var index = loadedPageIndex;
for(var i = 0; i < nextImageCount; i++)
{
window.setTimeout(function () {
$(".patentPageNew[id='" + index + "']").html("<img src='/Patent/GetPatentImage/#Model.Id?pageIndex=" + index + "' />");
index++;
var setValue = index;
$("#loadedPageIndex").attr("value", setValue);
}, 2000);
}
}
I was wondering what may be causing the function to stop working after the first div, or if there might be a better approach to what I'm attempting?
EDIT: It seems that loadedPageIndex == $(".patentPageNew").attr("id") within the if statement was the culprit.
#ViewBag.totalCount; is not a JavaScript, it's .NET, so your script probably stops after encountering an error.
Also: ".patentPageNew[id='" + loadedPageIndex + "']" is inefficient. Since IDs must be unique, just query by ID instead of by class name then by ID.

Categories

Resources