Javascript to make background image clickable? - javascript

I can't use a div because the CMS I am using won't allow html into the theme style (it's using a weird structure in its coding) and the only thing that I found that has worked is javascript but I don't know what javascript code will enable a clickable background image.
Any ideas?
<meta name="description" content="description here">
<script type="text/javascript">
document.backgroundImage = "url('http://mydomain.com/image.jpg')";
function callback() {
location.href = "http://mylink.com";
}
document.addEventListener("click", callback, false);
</script>
<script type="text/javascript"> //google analytics code </script>

this is the background of something right? This something has to receive the click event handler.
cheers.
edit: adding example:
Hypothesis:
o.id = "OhMyCuteness";
o.style.backgroundImage = "url('...')";
then:
o.addEventListener("click", callback, false);
and:
function callback(clickEvent) {
alert("They clicked meeeee buhuhuhu: " + clickEvent.target.id);
}
Edit2: in the case your document has a background this is exactly the same, use the document instead of the element "o" as a target for addEventListener.

Related

addEventListener to div element

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.

Change history using hash doesn't trigger a function neither changing with back button

I'm changing the background of some Links using JavaScript:
$(document).ready(function(){
$("#home").click( function(){
$("body").removeClass("bg2 bg3").addClass("bg1");
});
$("#link1").click( function(){
$("body").removeClass("bg1 bg3").addClass("bg2");
});
$("#link2").click( function(){
$("body").removeClass("bg1 bg2").addClass("bg3");
});
});
Bg1,2,3 are css classes of background (bg images). I prevent refresh button (to save BG) with hash:
var x = location.hash;
if (x==="#link1")
{
$ ("body").removeClass("bg1 bg3").addClass("bg2");
}
else if (x==="#link2")
{
$ ("body").removeClass("bg1 bg2").addClass("bg3");
}
});
It work but if i click on back button it doesn't change the background to previous link background. Is it possible to fix it except web storage/session storage? With hash or somethink like this?
When you hit the back button of your browser, the page will not reload because you are using the hash, this means to the browser that you want to move to a different anchor.
To proper manipulate the history stack you need to use the freaking awesome History API
To fix your problem you need to intercept the event triggered when your history stack change.
<html>
<head>
<script type="text/javascript" src="../lib/jquery.1.9.2.js"></script>
</head>
<body onload="checkHash();">
testing hash stuff
click to change
<script type="text/javascript">
console.log('loaded');
var checkHash = function(){
if(location.hash==="#black"){
$('body').css("background-color","black");
}else if(location.hash==="#white"){
$('body').css("background-color","white");
}
}
//the event below will be trigger when you hit backbutton or the link
window.addEventListener("popstate", function(e) {
console.log('trigger when hit the back button')
checkHash();
});
</script>
</body>
</html>
IE9 FIX
If you need to implement the same behavior on IE9 you must listen the onhashchange, so you can trigger the code to change the background when backbutton was clicked.
<body onhashchange="alert('trigger the background change function')">

I need to update my page using Anchor (#) in URL

index.php
<html>
<head>
<title>My Title</title>
<script type="text/javascript">
function getLink(data) {
document.getElementById("box").innerHTML="This is "+data;
}
</script>
</head>
<body>
Home<br />
Profile<br />
Message<br />
Setting<br />
<hr />
<div id="box"></div>
</body>
</html>
Output
Home
Profile
Message
Setting
This is Home
As the code says my Div contents updated when i click any of the link but the problem is that when user goes back by clicking Back Button of Browser the content of my Div donot changes.
I want that either user Goes Back, Goes Forward or he directly puts the path in the address bar www.*****/index.php#profile the content of my Div should be change.
Note
I used document.location.hash to get the value of hash like this :
<head>
<script>
var hashValue=document.location.hash;
alert(hashValue);
</script>
</head>
but it works only when user goes back and then refresh the page
Plz help me how can i achieve this :(
You need to use hashchange event:
function hash_changed() {
var data = document.location.hash.substr(1);
var box = document.getElementById("box");
if (data) {
// inner page
box.innerHTML="This is " + data;
}
else {
// homepage
box.innerHTML = "";
}
}
window.onhashchange = function () {
hash_changed();
};
window.onload = function () {
hash_changed();
};
Also when you are using hashchange event, there is
no need to set onclick for your links:
Home
Profile
Message
Setting
When user click on a link, the hash automatically changes (with href attribute of link),
and hashchange event get fired.
Check DEMO here.
First Time
When a user come to your page for the first time with a hash:
http://fiddle.jshell.net/B8C8s/9/show/#message
We must show the wanted page (message here), so we must run hash_changed() function
we declare above, at first time. For this, we must wait for DOM ready or window.onload.
Check the HTML5 history API. It allows you to work with the browser history
HTML5 history api
$(window).on('hashchange', function() {
alert(location.hash);
});
or window.onhashchange event if you don't want to use jQuery
If you're going to be using AJAX, you'll really want to look into using jQuery instead of raw javascript unless your intention is educational. jQuery is just a mainstay of the web now.
If you must use those hashes...
Use jQuery Special Events, and use the hashchange event:
<a href='#home'>Home</a>
Script:
$(window).on('hashchange', function() {
$('#box').html("This is "+event.fragment);
});
However, for your scenario...
You don't need to use those # values at all as you're passing the values in your function arguments anyway according to the code you provided, just do this:
Home<br />
Alternatively (and preferably, as you're using AJAX according to the tags) you can use jQuery and its builtin selector click events which use Event Listeners:
<a href='javascript:void();' class='divLink' id='home'>Home</a><br/>
Script is this easy:
$('.divLink').click(function(){
$('#box').html("This is "+$(this).id());
}

respond to key press javascript

I'm sorry if this is basic, but I've searched and found nothing that works.
I want to load a web page. When that page loads, it displays an image. I want to have the page automatically start listening for a right arrow key press. When that happens, a function in my script will change the image (that part I have gotten to work by using a button that reacts when clicked).
It's the listening for and reacting to a key press I cannot get to work. Note that I'm using Safari, but I would like if possible for it to work in firefox or IE as well.
Please help thanks.
UPDATE TO RESPOND TO COMMENT: Here is what I tried, though I simplified the other part to make this shorter -- now it just writes a result to a div:
<html>
<head>
<script language="Javascript">
function reactKey(evt) {
if(evt.keyCode==40) {
document.getElementById('output').innerHTML='it worked';
}
}
</script>
</head>
<body onLoad="document.onkeypress = reactKey();">
<div id="output"></div>
</body>
</html>
If you are using jquery, you can do this:
$(document).keydown(function(e){
if (e.keyCode == 39) {
alert( "right arrow pressed" );
return false;
}
});
document.onkeydown= function(key){ reactKey(key); }
function reactKey(evt) {
if(evt.keyCode== 40) {
alert('worked');
}
}
http://jsfiddle.net/dY9bT/1/
Easiest thing to do is use one of the many many many hotkey libraries, like https://github.com/jeresig/jquery.hotkeys or https://github.com/marquete/kibo.
EDIT: try something like this (after you've already loaded Kibo's javascript).
In your body statement, add the onload handler: <body onload="setuphandler">.
Then add something like this (taken from the Kibo page):
<script type="text/javascript">
var k = new Kibo();
function setuphandler()
{
k.down(['up', 'down'], function() {
alert("Keypress");
console.log('up or down arrow key pressed');
});
}
</script>

Setting click event with Javascript

I am trying to make a click event with Javascript on this image button
<input type="image" alt="Skip" name="bt_cancel" id="bt_cancel"
src="http://images.eversave.com/Images/optin/skip_button_092106.gif"
onclick="return handleSubmit(this);">
I am trying to use it in Chrome but it doesn't respond when I load the page.
I am using the following code:
if((window.location.hostname == "eversave.com")){
window.onload = function() {
document.getElementById("bt_cancel").click();
}
}
your code works absolutely fine, I think the problem is in the host name check. alert it to find out what it really is, like this: http://jsfiddle.net/AvgME/
<input type="image" alt="Skip" name="bt_cancel" id="bt_cancel"
src="http://images.eversave.com/Images/optin/skip_button_092106.gif"
onclick="return handleSubmit(this);">
<script>
if((window.location.hostname != "eversave.com")){
window.onload = function() {
document.getElementById("bt_cancel").click();
}
}
function handleSubmit(f) {
alert(window.location.hostname);
}
</script>
I think using jQuery is in your case a good option.
The code would than look like:
$(document).ready(function(){
$('#bt_cancel').click(function(){
// do some stuff with it like:
alert($(this).attr('src'));
});
});
You could just call the function:
handleSubmit(document.getElementById("bt_cancel"));
Btw. returning the value in the image click handler has no effect. There is no default action associated with clicking on images.
If the element is in the DOM on page-load, you can use this in the head of the document, otherwise put it after the </body> tag:
<script type="text/javascript">
var image = document.getElementByID('bt_cancel');
image.onclick = function(){
handlesubmit(this);
};
</script>
Though in all fairness, I think I prefer #Felix Kling's answer.

Categories