Javascript Onclicks not working? - javascript

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}

You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);

Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>

Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Related

Trying to make a jquery 'for' loop that adds div elements inside another div.

HTML:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' type='text/css' href='etch_a_sketch.css'/>
<script type='text/javascript' src='etch_a_sketch.js'></script>
</head>
<body>
<div class="outer">
</div>
</body>
</html>
JS:
$(document).ready(function() {
$(function() {
for(i=0; i<16; i++) {
$('<div class="inner"></div>').appendTo('.outer');
}
)};
Hello guys! I've tried looking for an answer here and elsewhere but with no luck. I'm trying to make a jquery 'for' loop that will dynamically make 16 div elements within an outer div container. The code looks sound to me but it's not working. I didn't post the CSS because it's irrelevant. Any help would be much appreciated!
First. You have syntax errors. Last line )}; should be }); .
Next. No need to create a jQuery object twice (there's a syntax too - } should be })).
This line:
$(document).ready(function() {
does the exact same thing as this line:
$(function() {
Reference
So, in summary, you should end up either with this:
$(document).ready(function() {
for(i=0; i<16; i++) {
$('<div class="inner">blah</div>').appendTo('.outer');
}
});
or this:
$(function() {
for(i=0; i<16; i++) {
$('<div class="inner">blah</div>').appendTo('.outer');
}
});
JSFiddle
Try this,
$(function() {
var innerHTML=[];
for(i=0; i<16; i++) {
innerHTML.push('<div class="inner"></div>');
}
$('.outer').html(innerHTML.join(''));
});
Please add jquery library to your page.
$(document).ready (function (){
for (var i=0; i<=16; i++){
$ ('.outer').html($('.outer').html()+"<div class='inner'></div>";
}
});
The above is seriously simple. Try that first. My theory would be that appendTo is not working because the element doesn't already exist? But it should work anyway? Also, you don't need the anonymous function within another.
You appear to be using jQuery, but haven't linked to the library. Add one of the following two lines (or download the file and link to that), depending on which version you want.
1.x snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
2.x snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Also there are some problems with brackets not being closed. The following snippet shows it working without the additional anonymous function within the ready handler.
$(document).ready(function() {
for (i = 0; i < 16; i++) {
$('<div class="inner">' + i + '</div>').appendTo('.outer');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
</div>
I want to suggest a better performance , it will speed up the process in case there is a lot of elements
$(document).ready(function() {
var innerDivs = "";
for(i=0; i<16; i++) {
innerDivs +='<div class="inner">blah</div>';
}
$('.outer').append(innerDivs);
});
This will perform better because we will not have to access the DOM tree more than one time

Adding click event to HTML5 template

How do you add a click event to a html5 template tag?
The following never registers a click event with the image:
<!doctype html>
<body>
<div id="content"></div>
<template id="itemTemplate">
foo
<img id='imageTag' src='image.png'>
</template>
<script>
var templ = document.querySelector('#itemTemplate');
templ.content.querySelector('#imageTag').click = function(){alert('xxxx');};
var content = document.querySelector('#content');
content.appendChild(templ.content.cloneNode(true));
</script>
</body>
Came across the same problem myself, and I will write what I have learned so others will have an answer as well.
As adenine commented, it's impossible to do it from inside the template. I tried that as well. What you could do, is complete the template creation, and when all the elements are registered in the DOM, you could add event listeners then.
So your code will look like:
<!doctype html>
<body>
<div id="content"></div>
<template id="itemTemplate">
foo
<img id='imageTag' src='image.png'>
</template>
<script>
var templ = document.querySelector('#itemTemplate');
var content = document.querySelector('#content');
content.appendChild(templ.content.cloneNode(true));
document.querySelector('#imageTag').click = function(){alert('xxxx');};
</script>
I used to have the same problem when I needed to add event listeners to an array of elements (trying to dynamically build a paginator), so I have used a forEach loop to give each element its click event:
for (var i = 0 ; i < totalPages ; i++) {
anchorElement.innerHTML = i + 1;
anchorElement.dataset.pageId = i + 1;
var clone = document.importNode(templateElement.content, true);
paginationContainer.appendChild(clone);
}
// Register pagination event listeners
document.querySelectorAll('.pagination a').forEach(function(anchorElement) {
$(anchorElement).on('click', function() {
alert('Hello');
});
});

onclick does not fire in a link that is created by clicking another link

Javascript function writelink creates a link that fires function hiya. It works when I define and invoke writelink inside script. But, I want the body to contain another link that calls writelink to create a link. This final link fails to fire (but works if I replace hiya with alert). I am a total novice, so I hope it is something obvious. The main idea is that I have to create some links from code, and these have to fire to execute some more code. (If you want me to do this a totally different way, please try to give me a complete example.)
<HTML>
<HEAD>
<script>
function hiya (num){
alert("hiya " + num);
}
function writelink (num){
var htmlstr = "link" + num + "";
document.write(htmlstr);
}
writelink(1);
</script>
</HEAD>
<BODY>
<br>
link2;
<br>
</HTML>
document.write(htmlstr) replaces the entire DOM with the link / htmlstr you are about to insert. Use pure javascript to create the link(s) instead :
function writelink(num){
var link = document.createElement('a');
link.innerHTML='link '+num;
link.href='#';
link.onclick=hiya(num);
document.body.appendChild(link);
}
Just replace writelink() with the code above.
You would typically want to add the link to a certain element instead of just <body>, lets say a <div> with the id menu :
var cnt = document.getElementById('menu');
cnt.appendChild(link);
update
<!doctype html>
<html>
<head>
</head>
<body>
link2
<script>
function hiya(num) {
alert("hiya " + num);
}
function writelink(num){
var link = document.createElement('a');
link.innerHTML='link '+num;
link.href='#';
link.onclick=function(e) {
hiya(num);
}
document.body.appendChild(link);
}
writelink(1);
</script>
</body>
</html>

creating a list in html using jQuery append not working

I've been staring at this code for hours now, any input appreciated.
I want to create a list in a HTML file from an array of objects using jquery append, but it justs stays blank.
HTML:
<html>
<head>
<script src="jquery-1.10.0.js"></script>
<script src="test.js"></script>
<title></title>
</head>
<body>
<div id="list">
</div>
<div id="template">
<div class="info">
<a class="url"></a>
</div>
</div>
</body>
</html>
Script:
function update(events) {
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
}
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
Assuming the JS code you show is contained in test.js, either move this line:
<script src="test.js"></script>
...to the end of the body (just before the closing </body> tag), or wrap your code in a $(document).ready() handler.
The way you currently have it, this line:
var eventList = $('#list')
...doesn't find the '#list' element because the script runs before the element is parsed. Same problem with finding '#template .info'.
You could wrap all of the code in a ready handler, or if you need to be able to call the update() function from elsewhere just wrap the initial call:
$(document).ready(function() {
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
});
Use the following JS code:
$(document).ready(function(){
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
});

How to run and display processing code (currently in part of the document.body) in an html canvas?

NOTE: I know I can import .pde files but I need to run code on screen so I will not be using this.
My three following attempts failed. I do not know which one was closer to achieving and I do not prefer one as long as it produces desired result. Appreciate the help by helping me get any of the attempts working/suggesting a new one.
1ST ATTEMPT) - use getText function written below but then some text that is not code can be found in the resulting jscode variable and thus the processing instance does not work.
function getText(n) {
var s = [];
function getStrings(n, s) {
var m;
if (n.nodeType == 3) { // TEXT_NODE
s.push(n.data);
}
else if (n.nodeType == 1) { // ELEMENT_NODE
for (m = n.firstChild; null != m; m = m.nextSibling) {
getStrings(m, s);
}
}
}
getStrings(n, s);
var result = s.join(" ");
return result;
}
var processingCode = getText(document.body)
processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = document.getElementById("mysketch");
var processingInstance = new Processing(canvas, jsCode);
....
<span class="sketch">
<canvas id="mysketch"></canvas>
</span>
2ND ATTEMPT) Same as above but added a tag with id="all_processing_code" but couldn't figure out how to get the text within anyway. This did not work:
var processingCode = getText(document.getElementbyId(all_processing_code));
3RD ATTEMPT) Removed getText and tried to use JQuery text() to isolate the code. Was having trouble mixing JS and Jquery though. Tried different stuff and none worked. What would be appropriate way to mix it in? What script type should I use? This was confusing.
<script type="text/jquery">
var processingCode = $('#all_processing_code').text();
//processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = $.Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = $(#'mysketch');
var processingInstance = new $.Processing($('canvas'), $('jsCode'));
}
</script>
First, check if your processing code is wrapped by an html element (like a div or something else) with an id. If it isn't, please do it!
For exemple:
<div id="mycode">
void setup() {
background(0);
}
</div>
After this, check if you have the getProcessingSketchId() function declared in your code. Processing IDE in JavaScript mode already exports html files with that function. If there isn't, please declare it inside your <head>:
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
You can include JQuery from google api including this line in your html before you use JQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
Assuming that you want to run your processing code when the page just has loaded, just append this code after the getProcessingSketchId() declaration.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
You can create this code inside any other <script type="text/javascript">.
At the end, you will have something like this:
<html>
<head>
<!-- Your title, meta tags, stylesheet and all other stuff here -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
</head>
<body>
<div id="mycode">
void setup() {
background(0);
}
</div>
</body>
</html>

Categories

Resources