Jquery appending to div - javascript

i am trying to append to a div with an ID that is dynamic
<script>
var GameId = "{{$match['gameId']}}";
var Ts = '{{$match['createDate']}}';
var TsInt = parseInt(Ts);
var timeSinceGame = moment(TsInt).fromNow();
$('#'+GameId).append(timeSinceGame );
</script>
the script is run inside of a php foreach loop.
the div ID is set the same as GameID variable
however nothing is appended to anything when run what's wrong here?

None of your jQuery is wrapped in DOM ready events, so the elements are likely not in the DOM yet when the code runs.
Try adding a DOM ready wrapper:
<script>
$(function(){
var GameId = "{{$match['gameId']}}";
var Ts = '{{$match['createDate']}}';
var TsInt = parseInt(Ts);
var timeSinceGame = moment(TsInt).fromNow();
$('#'+GameId).append(timeSinceGame );
});
</script>
$(function(){ is just a handy shortcut for $(document).ready(function(){
The alternative is to simply inject your code after the elements in the page, so that they do already exist.

Related

JQuery - element exists in code but returns 0 when using .length()

I have spent hours trying to figure out why the $('#news-main-container').html(itemlist); isn't working and found that when I use alert($('[id="news-main-container"]').length); it returns 0, implicating the element doesnt exist but I can see the element in the code when I inspect element. The itemlist is alerting but it won't insert into #news-main-container because it thinks it doesn't exist. Does anyone know what could cause this?
//get cached News JSON
function getNewsCache(){
cache['news'] = JSON.parse(localStorage.getItem('news'));
var objCache = cache['news'].data;
objCache = JSON.parse(objCache); //Parse string to json
buildNewsList(objCache);
}
//build HTML list of news items
function buildNewsList(objCache){
var itemlist='';
$.each(objCache, function(i, jd) {
var newstitle = jd.title.rendered;
var newsexcerpt = jd.excerpt.rendered;
var newscontent = jd.content.rendered;
var newsimageid = jd.featured_media;
var thumbsrc = '';
itemlist = itemlist+'<div class="content-news-box" id="newsclick" data-newscontent="'+newscontent+'" data-newstitle="'+newstitle+'"><div class="news-thumb-img"><img height="150px" src="'+thumbsrc+'"/></div><div class="news-title">'+newstitle+'</div><div class="news-excerpt">'+newsexcerpt+'<img height="40px" class="news-arrow-right" src="img/icon-arrow-right.png"/></div></div>';
});
alert(itemlist);
alert($('[id="news-main-container"]').length); //returns 0 but I can see it in the code!!
$('#news-main-container').html(itemlist); //WHY DOESNT THIS WORK?!?!?!
}
$("#load-news").click(function(event){
$('#stage').html('');
$('#stage').css('background','none');
$("#stage").load("news.html");
var data = {};
//get cache
cache['news'] = JSON.parse(localStorage.getItem('news'));
getNewsCache();
});
I re-arranged my code so that everything comes within $( "#stage" ).load( "news.html", function() { } and that works. Thanks #The_ehT, your suggestion got me there!
Most likely you run this code before DOM is rendered, so element doesn't exist at the runtime. Try enclosing your code in "document ready"
$(function(){
// Your code
});

jscript to run at window.onload AND item.onchange

I'm using jscript to load a string in to several elements of an array, then display the useful element in html.
There's a pulldown menu that causes the string to change. So, I need the function to be re-run when that happens.
I have been able to successfully display the element using window.onload
and, I have been able to successfully display the element AFTER the pulldown menu has been changed.
But, I can't seem to display the element with window.onload and subsequently after item.onchage
If anyone has any suggestions, I'd be grateful.
Here is the code that works for window.onload
window.onload = function() {
var selectedOptionId = jQuery('select').val();
var optionPartNumber = jQuery('input[name="OptID_' + selectedOptionId + '"]').val();
//loads the string in to an array and returns the 2nd element
var optionPartNumber = optionPartNumber.split(".")[1];
document.getElementById("MASNUM").innerHTML=optionPartNumber;
}
Here is the code that works for pulldown.onchange
jQuery(function(){
jQuery('.dropdownimage-format select').on('change', function(){
var selectedOptionId = jQuery('select').val();
var optionPartNumber = jQuery('input[name="OptID_' + selectedOptionId + '"]').val();
var optionPartNumber = optionPartNumber.split(".")[1];
document.getElementById("MASNUM").innerHTML=optionPartNumber;
});
In both cases, the element is displayed in html by
<a id="MASNUM">

jquery.appear - How to add on a canvas-element?

How to add the jquery.appear-Plugin to this canvas-element (id="pic")? The script itself is already included into the html-page, but how to make the canvas-image only visible, if the element is on the screen?
<canvas id="pic"></canvas>
<script type="text/javascript">
var picData6 = whatever1
var options = whatever2
var ct6 = document.getElementById("pic").getContext("2d");
ct6.canvas.width = document.getElementById("pic").offsetWidth-4;
ct6.canvas.height = document.getElementById("pic").offsetHeight;
var Chart6 = new Chart(ct6).Line(picData6,options);
</script>
It seems the .appear() has to be add somewhere. But where?
Thank you very much!
jQuery.appear simply gives you custom appear and disappear events for elements which you have registered.
To add it to your canvas, you would do something like:
// register the element with the plugin
$('#pic').appear();
// do this when it appears
$('#pic').on('appear', function(ev, elements) {
// elements is an array of elements which are now visible on the page
});

How to dynamically create list of <a> tags using js

I am creating html page which needs to create a list of links dynamically on a click of button. I know how to create this list when number of links to be created is known before like this:
//For 4 tags:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.innerHTML = "link1 text";
aTag.setAttribute('onclick',"func()");
mydiv.appendChild(aTag);
var bTag = document.createElement('b');
bTag.innerHTML = "link2 text";
bTag.setAttribute('onclick',"func()");
mydiv.appendChild(bTag);
var cTag = document.createElement('c');
cTag.innerHTML = "link3 text";
cTag.setAttribute('onclick',"func()");
mydiv.appendChild(cTag);
var dTag = document.createElement('d');
dTag.setAttribute('onclick',"func()");
dTag.innerHTML = "link4 text";
mydiv.appendChild(dTag);
But the problem is that the count will be known at run time and also on function call i need to identify the id of link that invoked function.. Can anybody help?
I don't know weather you receive or not the HTML to be shown in the anchor, but anyway, this should do the work:
function createAnchor(id, somethingElse) {
var anchor = document.createElement('a');
anchor.innerHTML = "link" + id + " text";
anchor.setAttribute("onclick", "func()");
return anchor;
}
Then you call the function like this:
function main(num_anchors) {
var mydiv = document.getElementById("myDiv");
for (var i = 0; i < num_anchors; i += 1) {
mydiv.appendChild(createAnchor(i));
}
}
Of course this code can be improved, but this is just for show how can this be possible.
Yes it is possible to do this at runtime .
JQuery provides very useful dom manipulation . So you can traverse the dom , filter what you need ..
you can find a lot of useful functions here .
http://api.jquery.com/category/traversing/
It would look something like this.
$( document ).ready(function() {
$( "a" ).each(function( index ) {
// enter code here..
}
});
document.ready gets invoked once the DOM has loaded.

Target child of children with .each() in jQuery

I’m iterating through the elements and grabbing the src attribute of the child of that element. I have this HTML code:
<noscript data-alt="super awesome">
<img src="http://farm9.staticflickr.com/8235/8585847956_39864361e3.jpg" alt="something" />
</noscript>
<noscript data-alt="super awesome">
<img src="http://farm9.staticflickr.com/8235/8585847956_39864361e3.jpg" alt="something" />
</noscript>
and jQuery:
$('body').children().each(function() {
var noscriptTag = $(this)[0];
var imgAlt = noscriptTag.getAttribute("data-alt");
var img_src = noscriptTag.find('img');
var img_regular = img_src.getAttribute("src");
console.log(img_regular);
});
But I’m getting this error:
Uncaught TypeError: Object #<HTMLElement> has no method 'find'
I also tried various other combinations (like $(this).find('img');) without making it work.
Here’s the demo: http://jsfiddle.net/LjWhw/
How do I target the img tag of that element? Thanks!
UPDATE: You can’t target elements which are inside <noscript> with JavaScript.
You are trying to call find jQuery function on DOM object, Use jQuery object instead of DOM javascript object to call find on it.
Change
var noscriptTag = $(this)[0];
To
var noscriptTag = $(this);
Edit: You will also need to change the code accordingly e.g. img_src.getAttribute("src"); to img_src[0].getAttribute("src"); or img_src.attr("src");
I would suggest you to do it this way:
$('body').children().each(function() {
var noscriptTag = $(this).find('noscript').first();
//---------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----this way
var imgAlt = noscriptTag.getAttribute("data-alt");
var img_src = noscriptTag.find('img');
var img_regular = img_src.attr("src");
console.log(img_regular);
});
try this
http://jsfiddle.net/UQJsy/1/
$('noscript').each(function () {
var noscriptTag = $(this);
var imgAlt = noscriptTag.attr("data-alt");
var img_src = noscriptTag.children('img');
var img_regular = img_src.attr("src");
alert(imgAlt);
});

Categories

Resources