i want to create labels dynamically using for loops...this is what i have done and its not working kindly help me solve this issue
$(document).ready(function() {
function create_labels(strt, end, overlay_body) {
for (var i = strt; i < end; i++) {
var labels=jQuery('<label id=lbl>hahahahha</label>');
labels.appendTo(overlay_body);
}
}
});
var strt = 9;
var end = 17;
var overlay_body = jQuery('<div id=overlay_body></div>');
overlay_body.appendTo(document.body);
create_labels(strt,end,overlay_body);
You should learn how to debug your javascript code.If you inspected the browser console you would know exactly what the problem is.To bring up the browser console in Google Chrome you can click Ctrl+Shift+J.
The problem is that the create_labels() function is not accessible outside of the jQuery load function.One way to fix this is to move the logic which calls this function inside the jQuery load:
$(document).ready(function () {
var strt = 9;
var end = 17;
function create_labels(strt, end, overlay_body) {
for (var i = strt; i < end; i++) {
var labels = jQuery('<label id=lbl>hahahahha</label><br />');
labels.appendTo(overlay_body);
}
}
var overlay_body = jQuery('<div id=overlay_body></div>');
overlay_body.appendTo(document.body);
create_labels(strt, end, overlay_body);
});
Related
I am trying to write the following script to lazyload background images of sub-menu on a website. But this function returns the error
Missing ) after argument list
My requirement is to load the background images after the window loaded completely. What i am doing is , I have added some data attributes to get the background image url, position etc. and then on windows load call this function which adds the css for the sub-menu.
<script>
function menuImageLazyLoad() {
var imgDefer = document.getElementsByClassName('megamenu-content');
for (var i = 0; i < imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-background-image')) {
imgDefer[i].css(
"background-image":+imgDefer[i].getAttribute('data-background-image'),
"background-position":+imgDefer[i].getAttribute('data-background-position'),
"background-repeat":+imgDefer[i].getAttribute('data-background-repeat')
);
console.log(imgDefer[i].getAttribute('data-background-image'));
}
}
}
window.onload = menuImageLazyLoad;
</script>
console logs returns the url of image:
url(image/sub_menu_image.jpg)
How can i fix this problem?
Update:
This is the final solution for my problem. I hope it may help someone
<script>
function menuImageLazyLoad() {
var imgDefer = document.getElementsByClassName('megamenu-content');
for (var i = 0; i < imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-background-image')) {
$(imgDefer[i]).css("background-image",imgDefer[i].getAttribute('data-background-image'));
$(imgDefer[i]).css("background-position",imgDefer[i].getAttribute('data-background-position'));
$(imgDefer[i]).css("background-repeat",imgDefer[i].getAttribute('data-background-repeat'));
}
}
}
window.onload = menuImageLazyLoad;
</script>
I guess you miss {}
For multiple attribute css settings,
It should be set as an object https://www.w3schools.com/jquery/jquery_css.asp
imgDefer[i].css(
{"background-image":+imgDefer[i].getAttribute('data-background-image'),
"background-position":+imgDefer[i].getAttribute('data-background-position'),
"background-repeat":+imgDefer[i].getAttribute('data-background-repeat')
});
I am "new" to JavaScript, making my first image- and media-slider for a website.
I have searched for answers in the web and here in SO, but they did not work for me.
My last big change was to divide my script into two parts. One outside of $(document).ready() and one inside. I want the user to be able to call a function via a button in the HTML. To make this possible this function has to be global and can not be located inside the $(document).ready(). Am I right?
Before I divided my script everything was inside the $(document).ready() area and it worked properly. But of cause I could not call the function via a button.
But now the part inside my $(document).ready(), which has to build the slider when the page is loaded, is not waiting for it. All my getElementById()'s are producing the error: "Can't set property 'style' of null." So the slider will not be built.
This is telling me getElementById() returns "null" even if it is inside $(document).ready().
HTML:
<!-- very content -->
<link href="...css" />
<script src="...js" />
<div id="slider"></div>
<!-- more content -->
<div id="changeContent"></div>
<!-- more content -->
</body>
</html>
JavaScript:
// Configuration
var slidersParentId = 'imslider';
var slideShowTitle = '';
var thumbnailWidth = 20;
var slidesWidth = 281.25;
var slidesHeight = 144.5625;
var currentSlideWidth = 500;
var currentSlideHeight = 257;
var nextSlideWidth = 375;
var nextSlideHeight = 192.75;
var prevSlideWidth = nextSlideWidth;
var prevSlideHeight = nextSlideHeight;
var resizeDifference = currentSlideWidth - nextSlideWidth;
var slidesMargin = 20;
var animationDistance = slidesWidth + slidesMargin;
var animationSpeed = 2000;
var intervalSpeed = 7000;
var contentDiv = "descriptif_site_spip";
// Variables from slides.json
var numberOfSlides;
var jsonSlides = {};
var bgImgUrl;
// Cache the DOM
var $slideShow = $('#'+slidersParentId);
var $slideInner;
var $slides;
var $slideNav;
var $navThumb;
var $thumb;
var $hovers;
var $content = document.getElementById(contentDiv);
// Other global Variables
var interval;
var currentSlide = 1;
var nextSlide = currentSlide + 1;
var prevSlide = currentSlide - 1;
var lastSlide = currentSlide;
var lastCurrentDif;
var lastNextSlide = lastSlide + 1;
var lastPrevSlide = lastSlide - 1;
var thumbImgs = [];
var navTo;
var interval;
var i;
// Global Variables for dragging
var dragStartPosition;
var dragStopPosition;
var draggedDistance;
var slidesDragged;
var posSlidesDragged;
var negSlidesDragged;
// IRIS-MEDIA-MODUS ?!
var iris_mode = 1;
//global functions...
//global warming...
$(document).ready(function(){
$.ajax({}
//getting some json...
});
// Building the slideshow windows
if (slideShowTitle !== 0) {
$slideShow.append('<h2 class="slideShowTitle">'+slideShowTitle+'</h2>');
}
$slideShow.append('<div id="outerWindow"><div id="innerWindowPositioner"<div id="innerWindow"></div></div</div>');
$slideInner = $slideShow.find('#innerWindow');
$slideInner.css({'width': numberOfSlides*slidesWidth+numberOfSlides*slidesMargin*currentSlideWidth*3});
// Building the slides & hovers
for (i=1; i<=numberOfSlides; i++) {
var idSlides = "slide_Nr"+i;
alert(idSlides);
var idHover = "hover_Nr"+i;
var j = i-1;
bgImgUrl = "url('" +jsonSlides[j].mediaUrl+ "')";
var title = jsonSlides[j].title;
var artUrl = jsonSlides[j].articleUrl;
var subtitle = jsonSlides[j].subtitle;
var text = jsonSlides[j].text;
var date = jsonSlides[j].date;
$slideInner.append('<div class="slide" id="'+idSlides+'"><div class="hover" id="'+idHover+'"></div></div>');
$('#'+idSlides).css('top', '56.21875px');
document.getElementById(idSlides).style.backgroundImage = bgImgUrl;
$('#'+idHover).append('<div class="hover-title"><h3>'+title+'</h3><span class="hover-subtitle">'+subtitle+'</span></div><span class="hover-date">'+date+'</span><br clear="all" /><p class="hover-text">'+text+'</p>');
}
$slides = $slideInner.find('.slide');
$hovers = $slides.find('.hover');
// Building the thumbnail navigation
$slideShow.append('<div id="slideShowNavigation"><ul id="navigationThumbnails"></ul></div>');
$slideNav = $slideShow.find('#slideShowNavigation');
$navThumb = $slideNav.find('#navigationThumbnails');
for (i=0; i<numberOfSlides; i++) {
thumbImgs[i] = jsonSlides[i].mediaUrl;
// alert(thumbImgs);
}
for (i=1; i<=numberOfSlides; i++) {
j = i-1;
var idThumbs = "thumb_Nr"+i;
bgImgUrl = "url('" +jsonSlides[j].mediaUrl+ "')";
$navThumb.append('<li class="thumb" id="'+idThumbs+'"></li>');
document.getElementById(idThumbs).style.backgroundImage = bgImgUrl;
}
$thumb = $navThumb.find('.thumb');
$( '<li class="year"> > 2000 > </li>' ).insertBefore( "#thumb_Nr62" );
$navThumb.prepend('<li class="year">1980 >> </li>');
$navThumb.append('<li class="year"> 2020 >></li>');
$navThumb.append('<br clear="both" />');
// ...some
// ...more
// ...functions
});
With this HTML-structure it is not working.
When I put the script-inclusion at the end of my HTML it works correctly and the slider will be built.
So why is my $(document).ready() firing too early?
I also tried $(window).load() but it hat no effect.
Or is there any why to make function inside $(document).ready() globally available without removing it from $(document).ready()?
Probably because your script is running before the rest of the page loads. Try using $(window).ready().
EDIT:
Had wrong function .load() I meant to have .ready()... Whoops!
My last big change was to divide my script into two parts. One outside of $(document).ready() and one inside. I want the user to be able to call a function via a button in the HTML. To make this possible this function has to be global and can not be located inside the $(document).ready().
Actualy, it can:
All global JavaScript objects, functions, and variables automatically become members of the window object.
I suppose you need something like this:
window.addEventListener('DOMContentLoaded', function () {
window.my_magic_function = function (/* my magic params */) {
/* doing my magic */
};
});
<button onclick="my_magic_function(/* my magic params */)">Do magic</button>
window.addEventListener('DOMContentLoaded', ...) equivalent to $(document).ready(...)
So i've been trying to wrap my head around this, all i'm trying to do is store a div name in a variable for easy editing, then allow it to be called in standard actions such as show/hide.
Without the variables, my code works fine but with them it will not load the div, i've done a console log to make sure it knows what the div name is based off the stored variable and it returns correctly.
Here is my code:-
var buttonActive = 0;
var yourMenuDiv = '.menu-menu-1-container';
$(function() {
$(yourMenuDiv).before('<div class="responsiveButton"><div id="rBBar"></div><div id="rBBar"></div><div id="rBBar"></div></div>');
$(yourMenuDiv).before('<div class="responsiveMenu"><div id="responsiveTitle"></div></div>');
$(yourMenuDiv + 'ul').clone().appendTo('.responsiveMenu');
$('.home #logoImage').clone().appendTo('#responsiveTitle');
console.log(yourMenuDiv);
$(window).resize(function() {
if ($(window).width() < 600) {
$(yourMenuDiv).hide();
$('.responsiveMenu, .responsiveButton').show();
}else{
$('.responsiveMenu').removeClass('expandMenu');
$('.responsiveButton').removeClass('expandMenuButton');
$('.responsiveMenu, .responsiveButton').hide();
$(yourMenuDiv).show();
buttonActive = 0;
}
});
$(function() {
if ($(window).width() < 600) {
$(yourMenuDiv).hide();
$('.responsiveMenu, .responsiveButton').show();
}else{
$('.responsiveMenu, .responsiveButton').hide();
$(yourMenuDiv).show();
buttonActive = 0;
}
});
$('.responsiveButton').click(function() {
if (buttonActive == 0){
$('.responsiveMenu').addClass('expandMenu');
$('.responsiveButton').addClass('expandMenuButton');
buttonActive = 1;
}else{
$('.responsiveMenu').removeClass('expandMenu');
$('.responsiveButton').removeClass('expandMenuButton');
buttonActive = 0;
}
});
});
Thank you
You should try something like:
var yourMenuDiv = $('.menu-menu-1-container');
and then just call the methods with: yourMenuDiv.methodHere.
In your code:
$(yourMenuDiv + 'ul').clone().appendTo('.responsiveMenu');
Does the above line work correctly? - I mean should there be a space character in between. Something like below:
$(yourMenuDiv + ' ul').clone().appendTo('.responsiveMenu');
and as a matter of interest. Does it make any difference if you place your first two lines of code:
var buttonActive = 0;
var yourMenuDiv = '.menu-menu-1-container';
after $(function() { ?
Trying to run the following code, but it works either way I need to:
if(my_condition){
$('body').append("<div id='loaddiv'><div>");
for(var i=1; i<=100; i++){
var dl = 0;
$('#loaddiv').load('/script/?p='+i);
dl = $('#loaddiv .standart-view tr').length;
alert(dl);
}
}
Thus, I have to get the number of tr-elements, which is the parent element with class standart-view, and his parents - div block c id = load214235, for each page, but constantly displays zeros in the Alert :( I tried to upgrade the code, adding all the code in the load-callback function, but still does not work ...
if(my_condition){
$('body').append("<div id='loaddiv'><div>");
for(var i=1; i<=100; i++){
var dl = 0;
$('#loaddiv').load('/folder/?p='+i, function(){
dl = $('#loaddiv .standart-view tr').length;
alert(dl);
});
}
}
+I have yet to load after going condition with break; firebug it just swears that break does not know that close ... How do I get out of the situation? I feel that something with a visibility of variables and data do not have time to load another page, and the script is running on. Jquery is connected, the rest of the code is working, including the functions of jquery, the hierarchy of elements on another page observed (number of tr should be).
First load is an Asynchronous call, you are treating it as synchronous. You are reading the content before the Ajax call is returned. Hence why it is always zero.
Second, when you do hook it up write, the content will end up writing on top of each other. You can not use load() and expect it to work in a loop.
Here is the basic idea:
(function () {
var pageCounter = 1;
var tableRowsTotal = 0;
max pageMax=10;
function loadPage() {
$.get('/folder/?p='+pageCounter, function(data){
var table = $(data).filter(".standart-view");
//or
//var table = $(data).find(".standart-view");
var rows = table.find("tbody tr");
var rowCount = rows.length;
console.log(pageCounter, rowCount);
tableRowsTotal += rowCount;
pageCounter++;
if(pageCounter<pageMax) {
loadPage();
} else {
console.log("done");
}
});
}
loadPage();
}());
In javascript I have a reference to a div. In that div is an anchor element with a name='foundItem'
How do I get a reference to the anchor with the name foundItem which is in the Div I have the reference of?
There are 'many' foundItem anchors in other divs on the page. I need 'this' DIVs one.
// assuming you're not using jquery or mootools
// assume div is mydiv
var lst = mydiv.getElementsByTagName('a');
var myanchor;
for(var i=0; i<lst.length; ++i) {
if(lst[i].name && lst[i].name == 'foundItem') {
myanchor = lst[i];
break;
}
}
// the mootools method
var myanchor = $(mydiv).getElement('a[name=foundItem]');
You can use the getElementsByTagName method to get the anchor elements in the div, then look for the one with the correct name attribute:
var found = null;
var e = divReference.getElementsByTagName('A');
for (var i=0; i < e.length; i++) {
if (e[i].name && e[i].name == 'foundItem') {
found = e[i];
break;
}
}
If found is not null, you got the element.
If you happen to use the jQuery library, you can let it do the searching:
var found = null;
var e = $(divReference).find('a[name=foundItem]');
if (e.length == 1) found = e.get(0);
Use a JavaScript library like jQuery and save yourself time.
var theAnchor = $('#divId a[name=foundItem]');
Using jquery, it's dead easy:
<script type="text/javascript">
$(function(){
var item = $("#yourDivId a[name=foundItem]")
)};
</script>
Update:
As per the comments, if you have control over what to id/name/class your anchor tag/s, it would be best to apply a class to them:
<div id="firstDiv">
test
</div>
<div id="secondDiv">
test another one
</div>
<!-- and so forth -->
<script type="text/javascript">
$(function(){
var item = $("#firstDiv a.foundItem");
alert(item.html()); // Will result in "test"
var item2 = $("#secondDiv a.foundItem");
alert(item2.html()); // Will show "test another one"
)};
</script>
If you're doing anything with javascript, jQuery saves you tons of time and is worth investing the effort to learn well. Start with http://api.jquery.com/browser/ to get an intro to what's possible.
Not sure if this helps, but wanted a function to handle the load of a page dynamically and scroll to the anchor of choice.
function scrollToAnchor(anchor_val) {
alert("" + anchor_val);
var page = document.getElementById('tables');
var found = null;
var cnt = 0;
var e = document.getElementsByTagName('a');
for (var i = 0; i < e.length; i++) {
if (e[i].name && e[i].name == anchor_val) {
found = e[i];
break;
}
cnt++;
}
if (found) {
var nPos = found.offsetTop;
alert("" + nPos);
page.scrollBy(0, nPos);
} else {
alert('Failed with call of scrollToAnchor()' + cnt);
}
}