I have a problem when calling 2 JS functions that work fine separately. I am not well versed in JS: I took the scripts from some posts here and adapted them, and I cannot make them work together. My goal is to make appear the side panel and to change the color of a box within that panel when clicking on the related link in the main text (and to undo it by clicking again on it).
This is the function that I use for showing the side panel:
function showRightPanel() {
var elem = document.getElementById("right-panel");
if (elem.classList) {
console.log("classList supported");
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
And this is the function for changing the color:
var els = document.getElementsByClassName('change-color'),
target = document.getElementById('footnotes'),
changeColor = function() {
target.style.backgroundColor = this.getAttribute('data-color');
};
for(var i=els.length-1; i>=0; --i) {
els[i].onclick = changeColor;
}
And this is the html that calls both functions it:
<a href="#footnote1-chapter1" class="change-color" data-color="#E0FFC2"
onclick="showRightPanel();changeColor();"></a>
And this is the box that has to appear and change color:
<div id="footnotes"><p class="footnote" data-id="footnote1-chapter1">
</p></div>
Both scripts are in separate .js files that are referred to in the header, and I know this might be the problem for the second script, as it was mentioned that:
"You should put the javascript at the end of your body (just before ), or wrap it in a function listening load or DOMContentLoaded event (e.g. using addEventListener). If not, document.getElementById is executed before the element is loaded to the DOM, so it return null. – " in this post change background color of div.
But I do not know how to "wrap it in a function listening load or DOMContentLoaded event".
Can someone please help me?
Thank you for your help in advance!
You could wrap your code in an on load function, but the general consensus seems to suggest putting your scripts at the end of the body tag instead, according to this StackOverflow answer and the YUI team. This accomplishes the same thing as wrapping your code, and might fix your problem if it's related to DOM dependencies.
So I would recommend you put your scripts at the end of your body tag instead of in your head tag, and see if that helps.
As Nathan mentioned, your anchor has the attribute onclick as onclick="showRightPanel();changeColor();"
But your javascript replaces this attribute, see: els[i].onclick = changeColor;
So only changeColor function will be called.
[update]
As in the comments, the accepted answer:
els[i].onclick = function(){showRightPanel();changeColor.apply(this);}
Related
when trying to ensure my webpage is using unobtrusive javascript I cant seem to get the onclick event to work in my javascript, it only works as an event in the html tag. here is the code
var dow = document.getElementById("dowDiv");
dow.onclick=function () {}
any reason that this isnt working for me? as all the answers i can find say this is the way to do it, thanks in advance
There could be several reasons based on the information provided.
Most likely, the event function code is being attached before the DOM has finished loading.
Alternatively, you might be using a browser which doesn't support onclick (though this is unlikely!). To guarantee it will work, you can use fallbacks for the main routes of attaching an event:
if (dow.addEventListener) {
dow.addEventListener('click', thefunction, false);
} else if (dow.attachEvent) {
dow.attachEvent('onclick', thefunction);
} else {
dow.onclick = thefunction;
}
Make sure that you only have one element with the id dowDiv. If you have z-index's on elements and something is over the div it might be blocking the click event on the div.
var dow = document.getElementById("dowDiv");
var out = document.getElementById("out");
var clickCount = 0;
dow.onclick = function() {
clickCount += 1;
out.innerHTML = clickCount
}
<div id="dowDiv">Hello onclick <span id="out"></span>!</div>
You can use jQuery to achieve a simple o'clock function.
Make you include jQuery BEFORE you reference your .js file:
<script src="path/to/jQuery.js"></script>
<script src="file.js></script>
With jQuery you can say
$('#dowDIV').click(function(){
Do stuff here;
})
I am trying to fire a script when the contents of a div are altered, specifically when a div receives the next set of results from a js loaded paginator.
I have this:
<script script type="text/javascript" language="javascript">
document.addEventListener("DOMCharacterDataModified", ssdOnloadEvents, false);
function ssdOnloadEvents (evt) {
var jsInitChecktimer = setInterval (checkForJS_Finish, 111);
function checkForJS_Finish () {
if ( document.querySelector ("#tester")
) {
clearInterval (jsInitChecktimer);
//do the actual work
var reqs = document.getElementById('requests');
var reqVal = reqs.get('value');
var buttons = $$('.clicker');
Array.each(buttons, function(va, index){
alert(va.get('value'));
});
}
}
}
</script>
This works well when the doc loads (as the results take a few seconds to arrive) but I need to narrow this down to the actual div contents, so other changes on the page do not fire the events.
I have tried:
var textNode = document.getElementById("sitepage_content_content");
textNode.addEventListener("DOMCharacterDataModified", function(evt) {
alert("Text changed");
}, false);
But the above does not return anything.
Can what I am trying to do be done in this way? If yes where am I going wrong?
Using Social Engine (Zend) framework with MooTools.
I did this in the end with a little cheat :-(
There is a google map loading on the page that sets markers to match the location of the results. So I added my events to the end this code namely: function setMarker() {}.
I will not mark this as the correct answer as it is not really an answer to my question, but rather a solution to my problem, which is localised to the Social engine framework.
I will add a Social engine tag to my original question in the hope it may help someone else in the future.
Thanks guys.
I've been wondering if there is a way to prevent my functions hiding any current text/formatting.
<body>
<script type="text/javascript">
document.body.style.backgroundColor = "#F5F0EB";
var page = 0
function flip(){
document.write(page);
page++;
}
</script>
<input type=button value="Next" onClick="flip()">
</body>
When I press the button I lose the coloured background and the text appears. Is there a way to make the background stay and the text appear?
Yes, by not using document.write(). MDN explains it clearly:
Writing to a document that has already loaded without calling
document.open() will automatically perform a document.open call.
And about document.open() it says:
If a document exists in the target, this method clears it.
What you should be doing, is manipulate nodes in the DOM. For example, you could change the inner HTML of the body:
document.body.innerHTML += page;
Alternatively, you could create a text node and append it:
var textNode = document.createTextNode(page);
document.body.appendChild(textNode);
In both cases, the current document is not flushed, it is only modified.
This is happening because you're writing non-html to a document which should be html. As indicated by others, it may also be clearing your existing html. Instead of using document.write, you may want to append new elements to your document.
You can do that using the document.createElement function and document.appendChild function.
Here's what a quick Google search brought back:
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
You are writing the page to document which is overwriting all over your HTML. Instead, write out the content to a DIV.
This should fix your background color problem as well.
Here is a JS Fiddle with an example.
<script type="text/javascript">
document.body.style.backgroundColor = "#F5F0EB";
var page = 0
function flip(){
document.getElementById("contentgoeshere").innerHTML=page;
page++;
}
</script>
<input type=button value="Next" onClick="flip()">
<div id="contentgoeshere">
</div>
Good luck.
As Mattias Buelens explained, document.write calls the open method, which clears the DOM, simply because -after loading- the document.close method is called automatically. There are a number of alternatives you can use, of course.
Use the innerHTML attribute of the body element, for example.
Using document.createElement and document.body.appendChild is an option, too
But perhaps it's worth taking into consideration that both methods have their downsides: using innerHTML allows you to inject badly formatted markup into the DOM, and could leave you vulnerable to XSS attacks.
Using document.createElement is slower (generally) and often requires more code, which in turn makes your script(s) less maintainable.
You could use something like this:
var flip = (function(tempDiv)
{//create a div once
var page = 0,
targetDiv = document.getElementById('contentgoeshere');//closure variables
//page is now no longer an evil global, and the target element into which
//we will inject new data is referenced, so we don't have to scan the DOM
//on each function call
return function(overridePage)//optional argument, just in case
{//actual flip function is returned here
overridePage = overridePage || page++;//new content
tempDiv.innerHTML = overridePage;//render in div that isn't part of the DOM
//any number of checks can go here, like:
if (tempDiv.getElementsByTagName('script').length > 0)
{
alert('Naughty client, trying to inject your own scripts to my site');
return;
}
targetDiv.innerHTML = tempDiv.innerHTML;
//or, depending on your needs:
targetDiv.innerHTML = tempDiv.innerText;//or the other way 'round
};
}(document.createElement('div')));
A couple of side-notes: as it now stands, this function won't work because the DOM has to be fully loaded for the closure to work. A quick fix would be this:
var flip;//undefined
window.onload = function()
{
flip = (function(tempDiv)
{
var page = 0,
targetDiv = document.getElementById('contentgoeshere');
return function(e)
{
tempDiv.innerHTML = e instanceof Event ? page++ : (e || page++);//ternary + logical or
//your [optional] checks here
targetDiv.innerHTML = tempDiv.innerHTML;
if (e instanceof Event)
{//this part is optional, but look it up if you want to: it's good stuff
e.returnValue = false;
e.cancelBubble = true;
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
return e;
};
}(document.createElement('div')));
//instead of using the HTML onclick attribute:
document.getElementById('buttonID').onclick = flip;//use as event handler
};
Note that window.onload causes memory leaks on IE<9, check this link for the solution to this issue
Quite a simple question, yet it has been bugging me all week!
Firstly, I do not expect someone to write me this huge piece of code, then me take it away and claim it for my own. Would prefer someone to actually help me write this :)
I am attempting to show a playlist on my website as a png image.
I have 2 playlists that must be shown.
The playlist will change on an image press.
I have 4 button images, 'CD1up', 'CD1down', 'CD2up' and 'CD2down'.
I would like to have these buttons changing what current playlist is being shown, but also showing the buttons correct state. For example, is playlist1 is being shown, then 'CD1up' must be shown, and 'CD2down' shown.
I would post my current code here, but I basically scrapped it all and decided to start from scratch since I'm terrible with web javascript.
All help is greatly appreciated!
I can basically fluent in HTML and CSS, but horrible at web javascript.
Some notes:
If you give each image an id attribute, you can use document.getElementById to get a reference to that element once the page is loaded.
Then you can set the src property on that element to a new URL to change the image.
Make sure your script tag is after the elements in the HTML (just before the closing </body> works) so that the elements exist when you want them.
You can add a click event handler to any element on the page. Most browsers support addEventListener but some older versions of IE still require you to use attachEvent to hook up the handler. So you see people with functions that look something like this:
function hookEvent(element, eventName, handler) {
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
}
else if (element.attachEvent) {
element.attachEvent("on" + eventName, handler);
}
else {
element["on" + eventName] = function(event) {
return handler.call(this, event || window.event);
};
}
}
So for example, if you have this img:
<img id="myImage" src="/path/to/img.png">
This cycles through four images on click:
<!-- This must be AFTER the `img` above in the HTML,
just before your closing /body tag is good -->
<script>
(function() {
var myImage = document.getElementById("myImage"),
images = [
"/path/to/img1.png",
"/path/to/img2.png",
"/path/to/img3.png",
"/path/to/img4.png"
],
index = -1;
hookEvent(myImage, "click", imageClick);
function imageClick() {
++index;
if (index >= images.length) {
index = 0;
}
myImage.src = images[index];
}
})();
</script>
You can get a lot of utility functionality and smooth over browser differences using a decent library like jQuery, YUI, Closure, or any of several others, although if all you want to do on the page is change the images sometimes and handle a click or two, that might be overkill.
I do not understand what's going on...
I have a simple userscript, that add couple DIVs, css styles and JS functions in the pages I visit
In particular, I have one DIV that trigger a JS function with a onClick listener - this function is a "toggle" function (display/hide an other DIV):
function togglegm(etat) {
if (etat = 'on') {
document.getElementById('greasemky').style.display = 'block';
document.getElementById('greasemkytoggle').innerHTML = '';
} else if (etat = 'off') {
document.getElementById('greasemky').style.display = 'none';
document.getElementById('greasemkytoggle').innerHTML = '';
}
}
var script2 = d.createElement('script');
script2.appendChild(d.createTextNode(togglegm));
(d.body || d.head || d.documentElement).appendChild(script2);
The DIV "greasemkytoggle" only contains a link with a onClick that trigger "togglegm('on'), and my objective is that when togglegm(on) is executed, the innerHTML of this DIV becomes a trigger for togglegm(off).
Now the weird part... when I click on my DIV greasemkytoggle, the function togglegm(on) is perfectly executed (greasemky is displayed), and the innerHTML is perfectly changed with a link for "togglegm(off)", BUT if I click again, then nothing happens.
I looked at the source code, and discovered that my JS function just disappeared (that's why nothing happened on the last click)! Now, there is an empty function replacing my togglegm():
<script>
scriptHolderArray1
</script>
Do you understand that kind of behaviour...?
I found nothing online for that kind of situation...
GreaseMonkey runs under a much more security conscience set of rules.
Attach the event listeners using the proper DOM3 (addEventListener) method.
It is never a good idea (in user scripts or general scripting) to assign Javascript through innerHTML.
It is never a good idea to use the "javascript:" pseudo-protocol.
The problems are etat = 'on' and etat = 'off'.
If you want to set values, use
etat = 'on'
etat = 'off'
If you want to compare, use:
etat == 'on'
etat == 'off'
Moreover, href="javascript:return(false);" throws an error on Firefox because there is a return outside a function (SyntaxError: return not in function). You should do href="javascript:void(0);", or return false at the end of the onclick event.
Anyway, I don't understand very well what you are doing here:
var script2 = d.createElement('script');
script2.appendChild(d.createTextNode(togglegm));
(d.body || d.head || d.documentElement).appendChild(script2);
You have a function togglegm loaded to browser's memory by a <script> element.
Then, you create a new <script> with that function and append it to the document, in order to load it to browser's memory again (I guess).
Why?