Foros del Web » Programando para Internet » Javascript »

Lanzar enlace automaticamente

Estas en el tema de Lanzar enlace automaticamente en el foro de Javascript en Foros del Web. Saludos a todos, quiero incorpar en mi página web el siguiente efecto: nada mas entrar, la página se oscurece y aperece en primer plano una ...
  #1 (permalink)  
Antiguo 29/07/2010, 18:42
 
Fecha de Ingreso: marzo-2008
Mensajes: 48
Antigüedad: 16 años
Puntos: 1
Lanzar enlace automaticamente

Saludos a todos,

quiero incorpar en mi página web el siguiente efecto: nada mas entrar, la página se oscurece y aperece en primer plano una imagen (no oscurecida) con un mensage.
He conseguido hacerlo mediando un script el problema es que para lanzarlo hay que hacer click (el codigo es el siguiente, el del script no lo pongo que es muy largo):

Código PHP:
<a href="Imagenes/instrucciones.png" rel="lightbox" title="Instrucciones">image #1</a> 
la imagen que se pone en primer plano es "instrucciones.png" y el script se lanza a través de rel="lightbox".

El problema es que quiero que ese enlace se lance automáticamente al abrir la pagina web, que no haga falta hacer click en "image #1".
No se si es posible.

Desde ya muchas gracias!
  #2 (permalink)  
Antiguo 29/07/2010, 18:54
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Lanzar enlace automaticamente

pues con PHP no lo puedes hacer... necesitas Javascript...
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 30/07/2010, 06:30
 
Fecha de Ingreso: marzo-2008
Mensajes: 48
Antigüedad: 16 años
Puntos: 1
Respuesta: Lanzar enlace automaticamente

mmmmmm.... y alguien sabe como hacerlo con javascript???

Pd: si alguien puede mover el hilo allí, me ahorro el duplicarlo. Gracias
  #4 (permalink)  
Antiguo 30/07/2010, 08:35
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Tema movido desde PHP a Javascript
  #5 (permalink)  
Antiguo 30/07/2010, 09:59
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Lanzar enlace automaticamente

Creo que algo del tipo
Código Javascript:
Ver original
  1. window.onload = function(){
  2.  document.getElementById('enlace').onclick();
  3. }
podría funcionar, pero para eso se necesitaría que el atributo onclick estuviera declarado y que hiciera aparecer la ventana que necesitas. Es decir, sería algo así:
Código HTML:
Ver original
  1. <a rel='ligthbox' id='enlace' onclick='apareceLaVentana()' title='Instrucciones'>image #1</a>

Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #6 (permalink)  
Antiguo 02/08/2010, 08:23
 
Fecha de Ingreso: marzo-2008
Mensajes: 48
Antigüedad: 16 años
Puntos: 1
Respuesta: Lanzar enlace automaticamente

Muchas gracias Cronos! Pero no es lo que estoy buscando.

Me gustaría que sin tener que hacer click ni nada por el estilo se produjese el efecto que quiero. Es decir, mada mas abrir la página, se pusiera el fondo oscurecido y sobre el fondo, centrado, apareciese la imagen que quiero.
Lo tengo todo escepto el hecho de que el script que lo hace se cargue automáticamente, sin necesidad de hacer click en el enlace.

Muchas gracias!
  #7 (permalink)  
Antiguo 02/08/2010, 15:01
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: Lanzar enlace automaticamente

Prueba este código y verás lo que te quiero decir
Código Javascript:
Ver original
  1. window.onload = function(){
  2.  document.getElementById('hazClick').onclick();
  3. }
Código HTML:
Ver original
  1. <div onclick='alert(this.id);' id='hazClick'>Haz Click!</div>

Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #8 (permalink)  
Antiguo 11/08/2010, 19:09
 
Fecha de Ingreso: marzo-2008
Mensajes: 48
Antigüedad: 16 años
Puntos: 1
Respuesta: Lanzar enlace automaticamente

Gracias Cronos, pero no es lo que busco.
Voy a intentar explicarlo mas claramente:

Tengo el siguiente código javascript en un archivo llamado lightbox.js que cuando alguien pincha en el enlace, se ejecuta: (lo pongo en dos post porque es demasiado extenso)

Código HTML:
var loadingImage = 'loading.gif';		
var closeButton = 'close.gif';		
//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//

function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){ hideLightbox(); }
}


//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }
	

//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
function showLightbox(objLink)
{
	// prep objects
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objImage = document.getElementById('lightboxImage');
	var objLoadingImage = document.getElementById('loadingImage');
	var objLightboxDetails = document.getElementById('lightboxDetails');

	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// center loadingImage if it exists
	if (objLoadingImage) {
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}

	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';

	// preload image
	imgPreload = new Image();

	imgPreload.onload=function(){
		objImage.src = objLink.href;

		// center lightbox and make sure that the top and left values are not negative
		// and the image placed outside the viewport
		var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
		var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);
		
		objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";


		objLightboxDetails.style.width = imgPreload.width + 'px';
		
		if(objLink.getAttribute('title')){
			objCaption.style.display = 'block';
			//objCaption.style.width = imgPreload.width + 'px';
			objCaption.innerHTML = objLink.getAttribute('title');
		} else {
			objCaption.style.display = 'none';
		}
		
		// A small pause between the image loading and displaying is required with IE,
		// this prevents the previous image displaying for a short burst causing flicker.
		if (navigator.appVersion.indexOf("MSIE")!=-1){
			pause(250);
		} 

		if (objLoadingImage) {	objLoadingImage.style.display = 'none'; }

		// Hide select boxes as they will 'peek' through the image in IE
		selects = document.getElementsByTagName("select");
        for (i = 0; i != selects.length; i++) {
                selects[i].style.visibility = "hidden";
        }

	
		objLightbox.style.display = 'block';

		// After image is loaded, update the overlay height as the new image might have
		// increased the overall page height.
		arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');
		
		// Check for 'x' keypress
		listenKey();

		return false;
	}

	imgPreload.src = objLink.href;
	
}
  #9 (permalink)  
Antiguo 11/08/2010, 19:10
 
Fecha de Ingreso: marzo-2008
Mensajes: 48
Antigüedad: 16 años
Puntos: 1
Respuesta: Lanzar enlace automaticamente

Código HTML:
//
// hideLightbox()
//
function hideLightbox()
{
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');

	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';

	// make select boxes visible
	selects = document.getElementsByTagName("select");
    for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}

	// disable keypress listener
	document.onkeypress = '';
}

//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
function initLightbox()
{
	
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
			anchor.onclick = function () {showLightbox(this); return false;}
		}
	}

	// the rest of this code inserts html at the top of the page that looks like this:
	//
	// <div id="overlay">
	//		<a href="#" onclick="hideLightbox(); return false;"><img id="loadingImage" /></a>
	//	</div>
	// <div id="lightbox">
	//		<a href="#" onclick="hideLightbox(); return false;" title="Click anywhere to close image">
	//			<img id="closeButton" />		
	//			<img id="lightboxImage" />
	//		</a>
	//		<div id="lightboxDetails">
	//			<div id="lightboxCaption"></div>
	//			<div id="keyboardMsg"></div>
	//		</div>
	// </div>
	
	var objBody = document.getElementsByTagName("body").item(0);
	
	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();

	// preload and create loader image
	var imgPreloader = new Image();
	
	// if loader image found, create link to hide lightbox and create loadingimage
	imgPreloader.onload=function(){

		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
		objOverlay.appendChild(objLoadingImageLink);
		
		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);

		imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs

		return false;
	}

	imgPreloader.src = loadingImage;

	// create lightbox div, same note about styles as above
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	
	// create link
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	objLink.setAttribute('title','Click to close');
	objLink.onclick = function () {hideLightbox(); return false;}
	objLightbox.appendChild(objLink);

	// preload and create close button image
	var imgPreloadCloseButton = new Image();

	// if close button image found, 
	imgPreloadCloseButton.onload=function(){

		var objCloseButton = document.createElement("img");
		objCloseButton.src = closeButton;
		objCloseButton.setAttribute('id','closeButton');
		objCloseButton.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objLink.appendChild(objCloseButton);

		return false;
	}

	imgPreloadCloseButton.src = closeButton;

	// create image
	var objImage = document.createElement("img");
	objImage.setAttribute('id','lightboxImage');
	objLink.appendChild(objImage);
	
	// create details div, a container for the caption and keyboard message
	var objLightboxDetails = document.createElement("div");
	objLightboxDetails.setAttribute('id','lightboxDetails');
	objLightbox.appendChild(objLightboxDetails);

	// create caption
	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objCaption.style.display = 'none';
	objLightboxDetails.appendChild(objCaption);

	// create keyboard message
	var objKeyboardMsg = document.createElement("div");
	objKeyboardMsg.setAttribute('id','keyboardMsg');
	objKeyboardMsg.innerHTML = 'press <a href="#" onclick="hideLightbox(); return false;"><kbd>x</kbd></a> to close';
	objLightboxDetails.appendChild(objKeyboardMsg);


}




//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}

}

addLoadEvent(initLightbox);	// run initLightbox onLoad
Para lanzarlo utilizo el siguiente enlace:

Código HTML:
<a href="Imagenes/instrucciones.png" rel="lightbox" title="Instrucciones">image #1</a> 
Mi intencion es modificar el codigo javascript para que no sea necesario pinchar en el enlace. Quiero que se ejecute automaticamente si al entrar en la página el visitante cumple una serie de caracteristicas.

Un saludo y muchas gracias por vuestra ayuda.[/HTML]
  #10 (permalink)  
Antiguo 12/08/2010, 00:17
 
Fecha de Ingreso: marzo-2008
Ubicación: Guatemala
Mensajes: 76
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: Lanzar enlace automaticamente

bueno ya tienes el código para hacerlo, lo que necesitas es activarlo al entrar (sin que el usuario haga nada) cierto? pues tienes varias opciones para lograrlo

una es poner un javascript que llame la función, tu procedimiento... y que se ejecute al final del tu documento, es decir, que sea de las últimas líneas en tu html

la otra es que pongas a correr tu función asociada al body onload. De esta manera tu página entera va a cargar y al justo finalizar la carga ejecutará el script, la función que le digas

y otra podría ser que le pongas a tu script un timeout, por decirte que programe tu función a correr a los 5 segundos de ser llamada, ahi está todo.
  #11 (permalink)  
Antiguo 12/08/2010, 02:19
 
Fecha de Ingreso: marzo-2008
Mensajes: 48
Antigüedad: 16 años
Puntos: 1
Respuesta: Lanzar enlace automaticamente

Si, cierto. Debe ejecutarse sin que el usuario haga nada.
La segunda opción es la que busco. Que se ejecute la funcion javascript al terminar de cargar la página completa.
El problema es que no se mucho de javascript y no se como podría hacer eso.
Tampoco se modificar el código javascript que ya tengo para que tenga en su interior la imagen que quiero cargar (la que actualmente se le pasa al pincha en el enlace).

Alguna sugerencia???

Muchas gracias por la ayuda, estoy aprendiendo mucho.
  #12 (permalink)  
Antiguo 12/08/2010, 09:44
 
Fecha de Ingreso: marzo-2008
Mensajes: 48
Antigüedad: 16 años
Puntos: 1
Respuesta: Lanzar enlace automaticamente

Alguna idea??? Estoy completamente perdido!

Muchas gracias!

Etiquetas: automaticamente, enlace, lanzar
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:01.