call a javascript function inside a div - javascript

I would like to create a webpage which contains several divs each containing the same draw function with different implementation (like a generic interface). After loading the page I want to iterate through all the divs and call each draw function one after the other.
My page so far looks like this:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
</head>
<body>
<script type='text/javascript'>
$( document ).ready( function() {
// Draw all slots
$('div.slot').each(function(i, d) {
console.log('slot found: ' + d.id);
// d.draw() does not work
draw();
});
});
</script>
<div class="slot" id="slot1">
<script type='text/javascript'>
function draw() {
console.log('Here we draw a circle');
};
</script>
</div>
<div class="slot" id="slot2">
<script type='text/javascript'>
function draw() {
console.log('Here we do something totally different and draw a rectangle');
};
</script>
</div>
</body>
</html>
Unfortunately I don't know how to call the draw function of the selected div "d".
Right now it only calls the last defined draw function.
Update:
Mind you that I can not combine the different draw methods into one which would get a parameter like shape handed in. The draw methods will be totally independent from each other.

Why are you defining scripts in the divs?
Do your logic all in one script block:
<head>
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
</head>
<body>
<script type='text/javascript'>
$( document ).ready( function() {
// Draw all slots
$('div.slot').each(function(i, d) {
console.log('slot found: ' + d.id);
// d.draw() does not work
draw();
});
});
function draw(behavior) {
console.log(behavior);
}
</script>
<div class="slot" id="slot1" data-behavior="drew 1">
</div>
<div class="slot" id="slot2" data-behavior="drew 2">
</div>
</body>
</html>
If you're looking to do something more complicated, you should consider building an object oriented javascript application, with each block's functionality derived from a class "slot".
https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript

You can call it like
HTML:
<div class="slot" id="slot1">Draw1</div>
<div class="slot" id="slot2">Draw2</div>
JS:
function draw()
{
console.log('Drawed! '+$(this).attr('id'));
}
$(document).ready( function() {
$('div.slot').each(function(i, d) {
console.log('slot found: ' + d.id);
draw.call($(this));
});
});
An Example.
​

The reason that is happening is because you keep overwriting the draw function. Why don't you have a script page where you hold an array of function pointers to the right function like so:
var array = (draw1, draw2, draw3, ...);
function draw1()
{
//do your thing on div1
}
...
function drawn()
{
//do your n thing on divn
}
Now for your first div you need to call draw1 which is located at index 1 of the array.
HTML:
<div id="draw1">
</div>
....
<div id="drawn">
What do ya think. Note sytax has not been tested.

<html>
<head>
<script>
$(document).ready(
function() {
$('#show').call(callfun());
});
</script>
</head>
<body>
<h:form>
<div id="show" align="center">
<script>
function callfun(){
var data = "hi";
alert(data);
}
</script></div>
</h:form>
</body>
</html>
I think it may work.

Problem
You keep overwriting window.draw() every time you redefine it. You either need to namespace each one (that is, attach it to an (otherwise empty) object), or to give each and every function a distinct name. There is no "div-scope" in Javascript ;)
Solution
You can name each function according to the div's id and call it dynamically using the object["methodName"]() syntax to call it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
</head>
<body>
<script type='text/javascript'>
$( document ).ready( function() {
// Draw all slots
$('div.slot').each(function(i, d) {
console.log('slot found: ' + d.id);
// d.draw() does not work
window[d.id];
});
});
</script>
<div class="slot" id="slot1">
<script type='text/javascript'>
function slot1() {
console.log('Here we draw a circle');
};
</script>
</div>
<div class="slot" id="slot2">
<script type='text/javascript'>
function slot2() {
console.log('Here we do something totally different and draw a rectangle');
};
</script>
</div>
</body>
</html>
http://jsbin.com/mogeluzicu/1/edit?html,console

The easiest way I've found to go 'real OOP' in this case is to dispatch all on events on document level :
create a simple object and load this object in the main and the views like :
var events = {someCustomEventFromMain:'someCustomEventFromMain', someCustomEventFromView:'someCustomEventFromView'}
Now you can trigger events on document with jQuery like
$(document).trigger(events.someCustomEventFromMain, somedata);
And you can listen from any view or div or else
$(document).on(events.someCustomEventFromMain, function(__e, __data){
//___e is the event emitted from __e.target
//__data is the data object you wish to pass with the event
//do something when event occurs
});
So if every subscript listens to some event at document level, in your case 'drawEvent',that should do the trick. You can even pass a parameters in the data of the event, like 'circle'.
Hope this helps.

Related

Drawing .svg with javascript module "RDKIT-JS"

first of all I'm relatively new to javascript. So I'm sorry if my question is dumb. I would like to draw a molecule on my webiste by using this tool https://github.com/rdkit/rdkit-js. I also found an example here https://iwatobipen.wordpress.com/2021/12/29/create-desktop-chemoinformatics-application-with-js-chemoinformatics-rdkit-js/comment-page-1/. This example works in my case but when i try to invoke a function to draw a molecule as a .svg without using the example code, I fail. I get this error-message in my browser:
Uncaught ReferenceError: RDKit is not defined
at drawmol (results:21:15)
at results:33:5
In the following code example you can see the first case where it works and the second case were it doesn't. In both cases i use the same function.:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/#rdkit/rdkit/dist/RDKit_minimal.js"></script>
<title>Document</title>
<script>
window
.initRDKitModule()
.then(function (RDKit) {
console.log("RDKit version: " + RDKit.version());
window.RDKit = RDKit;
})
.catch(() => {
});
</script>
<script> var drawmol = function() {
var mol = RDKit.get_mol("C1=CC=C(C=C1)O"); // the string here is a string representation of chemical molecules, it could also be something like "CO" or "CCCCC", shouldnt be important
var svg = mol.get_svg();
document.getElementById("drawer").innerHTML = svg;
};
</script>
</head>
<body>
<button type='button' onclick='drawmol()'> <!-- this works -->
draw
</button><br>
<script>
// drawmol() //this doesnt work
</script>
<div id='drawer'></div>
</body>
</body>
</html>
Later i would like to use the module to dynamically make those images. I use django as the framework. In this case i tried to present a minimal example without the django stuff.
Thanks in advance for your effort!
You are calling drawmol() before RDKit is ready.
To fix this, place it after RDKit is loaded:
window
.initRDKitModule()
.then(function (RDKit) {
console.log("RDKit version: " + RDKit.version());
window.RDKit = RDKit;
//Now RDKit is loaded you can safely call drawmol()
drawmol();
})
.catch(() => {
});

Using document.addEventListener breaks document.getElementById

really hope someone can help me out here. Cutting a very long story short, on a few replies on this site I've seen people write that we should move away from:
<body onLoad="init();">
In the HTML to:
document.addEventListener("DOMCONTENTLOADED", init, false);
In the JavaScript file so we aren't mixing interactive code with content code etc.
But by switching to this method my code breaks, I can no longer access the DOM tree, here is an example:
function Tester(){
this.value1 = 10;
this.container = document.getElementById("fred");
this.list = this.container.childElementCount;
this.in_func = function(){
alert(this.value1+" "+ this.list);
};//end of this.in_func
}//end of function Tester
function init(){
var alpha = new Tester();
alpha.in_func();
}//end of function init
document.addEventListener("DOMCONTENTLOADED", init(), false);
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body><!--onLoad="init();"-->
<section id="fred">
<section id="elem1"></section>
<section id="elem2"></section>
<section id="elem3"></section>
<section id="elem4"></section>
<section id="elem5"></section>
</section>
</body>
</html>
The this.container is always null so the childElementCount generates an error of:
"Uncaught TypeError: Cannot read property 'childElementCount' of null"
Yet when I comment out the event listener and use the onLoad technique it works, am I just doing something stupid? I've tried using a variable instead of using this.list, tried using querySelector instead of getElementById, I've tried "load" instead of "DOMCONTENTLOADED" but nothing seems to work.
I know it will be something really simple but I cannot find the solution anywhere online, maybe I am just searching for the wrong thing.
Please put me out of my misery.
thanks
Zen
This is the correct way of doing it:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
function Tester(){
this.value1 = 10;
this.container = document.getElementById("fred");
this.list = this.container.childElementCount;
this.in_func = function(){
alert(this.value1+" "+ this.list);
};//end of this.in_func
}//end of function Tester
function init(){
var alpha = new Tester();
alpha.in_func();
}//end of function init
document.addEventListener("DOMContentLoaded", function(event) {
init();
console.log("DOM fully loaded and parsed");
});
// document.addEventListener("DOMContentLoaded", init(), false);
</script>
</head>
<body>
<section id="fred">
<section id="elem1"></section>
<section id="elem2"></section>
<section id="elem3"></section>
<section id="elem4"></section>
<section id="elem5"></section>
</section>
</body>
</html>
In you code you called init() and then passed it, but you should passed it as a function! document.addEventListener("DOMContentLoaded", init, false);
That's why
document.addEventListener("DOMCONTENTLOADED", init(), false);
Problem 1
You are calling init immediately and trying to use its return value as the event handler.
Remove the ().
Problem 2
Event names are case sensitive. It is DOMContentLoaded not DOMCONTENTLOADED

jQuery.contains() does not work properly

I should get an "alert" in the following case, but I am not getting any "alert". I am trying a simple example of jQuery.Contains().
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var alpha = $.contains('body','p') {
alert(alpha);
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
As per the jQuery documentation the API takes only element nodes (not JavaScript/jQuery objects or selectors)
Check to see if a DOM element is a descendant of another DOM element.
Only element nodes are supported; if the second argument is a text or
comment node, $.contains() will return false.
Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.
you should change the code to
$(function () {
alert($.contains(document.body, $("p")[0])) //alerts true
alert($.contains(document.body, document.getElementsByTagName("p")[0])); //alerts true
})
Try this:
$(document).ready(function(){
var alpha = $.contains(document.body,$("p")[0])
if (alpha) {
alert(alpha);
}
});
DEMO
Arguments are always DOM elements, not simple text.
For more details, see this.
jQuery.contains only returns boolean and doe not have a callback.
Try this code.
$(document).ready(function(){
alert($.contains(document.body,$('p')[0]));
});
Use this code you have error on this line (var alpha = $.contains('body','p'){)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var alpha = $.contains('body','p');
alert(alpha);
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>

JQuery partly triggered

I'm a beginner with JQuery and I was trying to create a button that dynamically changes the colors defined in the CSS depending on what color it is right now (just switch between blue / red) and also change the text on the button.
The .draggable() part executes just fine and so does the first and last console.log, so everything but the part within the click event handler works ... but why?
Relevant html code:
<!DOCTYPE html>
<html>
<head>
<title>Meine Website</title>
<meta charset="utf-8">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript">
</script>
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"
type="text/javascript">
</script>
<script src="home_jquery.js"></script>
<script src="home_javascript.js"></script>
<link rel="stylesheet" type="text/css" href="home_style_blau.css">
</head>
<body>
<input type="button" id="farbwechsel_button" value="Rot" />
/* rest of html (taschenrechner_box, etc.) */
</body>
Here's the jQuery part:
var blau = true;
$(document).ready(function () {
$('#taschenrechner_box').draggable();
console.log("test1");
$('#farbwechsel_button').click(function() {
console.log("test2");
if (blau == true) {
console.log("blau = " + blau);
$('body').css({"background-color": "8b0000"});
$('#farbwechsel_button').value = "Blau";
blau = false;
}
else {
console.log("blau = " + blau);
$('body').css({"background-color": "lightsteelblue"});
$('#farbwechsel_button').value = "Rot";
blau = true;
}
console.log("test3");
})
console.log("test4");
});
In your HTML you have:
<input type="button" id="farbwechsel_button" value="Rot" />
But in your JS you refer to
$('#farbwechel_button').click(function() {
Note the forgotten s in your JS. So the JS should be:
$('#farbwechsel_button').click(function() {
Edit: you've forgotten the s in al your referrals to the button. Don't forget to add it everywhere. You've also forgotten a ; just before the last console.log() function.
Edit 2: Here's a Fiddle with a working example. It's pretty much self explanatory. In this case you preferably should make use of classes which you toggle on pressing the button.

automatic reload of div container

instead of a whole page refresh after a certain time, i'd just like a specific div container to reload/refresh. is there any way to do this?
<div id="wrapper">
<div id="quoteContainer"></div>
</div>
You can get the effect you desire with jQuery and Googles ajax api
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_latest_scores').load('latest_scores.html');
}, 10000); // refresh every 10000 milliseconds
</script>
<body>
<div id="load_latest_scores"> </div>
</body>
If you had a page that served quotes, like quote.html for example, you could do this:
setInterval(refreshQuote, 10000); //every 10 seconds
function refreshQuote() {
$("#quoteContainer").load("quote.html");
}
In this case the expected return from quote.html (or whatever source you have) it a simple string that is the quote, it will take this and replace the content of <div id="quoteContainer"></div> with it.
i think that one aproach would be
<script>
function render (){
$('#mydiv').html("<b>new stuff</b>")
}
window.setInterval(render, 500);
</script>

Categories

Resources