IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Savoir si un element est visible a l'écran


Sujet :

JavaScript

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Mai 2009
    Messages
    15
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2009
    Messages : 15
    Points : 11
    Points
    11
    Par défaut Savoir si un element est visible a l'écran
    Bonjour a tous

    Je cherche à savoir si un element est visible a l'écran. L'objectif étant qu'a chaque fois que je scroll que je regarde si 10 elements de ma page apparaissent ou non a l'écran.

    En cherchant sur le net j'ai trouvé un forum américain ou un membre avait posté une fonction mais ça ne fonctionne pas avec moi.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    var projets = new Array();
    projets[0]="toto";
    projets[1]="tata";
    projets[2]="titi";
    projets[3]="tutu";
     
    window.onscroll = function (e) {  
    	for (var i = 0; i < projets.length; i++) {
    		if (checkvisible($('#' + projets[i]))) {
    			alert(projets[i]) + " est visible");
    		}
    	}
    } 
     
    function checkvisible( elm ) {
        var vpH = $(window).height(), // Viewport Height
            st = $(window).scrollTop(), // Scroll Top
            y = $(elm).offset().top;
     
        return (y > (vpH + st));
    }
    des idées ??

  2. #2
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 058
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 058
    Points : 44 588
    Points
    44 588
    Par défaut
    Bonsoir,
    En cherchant sur le net j'ai trouvé un forum américain ou un membre avait posté une fonction mais ça ne fonctionne pas avec moi.
    oui mais encore qu'est ce qui ne marche pas ?

  3. #3
    Membre à l'essai
    Profil pro
    Inscrit en
    Mai 2009
    Messages
    15
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2009
    Messages : 15
    Points : 11
    Points
    11
    Par défaut
    Le if (checkvisible($('#' + projets[i]))) { n'est jamais bon...

  4. #4
    Rédacteur

    Avatar de danielhagnoul
    Homme Profil pro
    Étudiant perpétuel
    Inscrit en
    Février 2009
    Messages
    6 389
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 73
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant perpétuel
    Secteur : Enseignement

    Informations forums :
    Inscription : Février 2009
    Messages : 6 389
    Points : 22 933
    Points
    22 933
    Billets dans le blog
    125
    Par défaut
    Bonsoir

    C'est du jQuery !

    J'ai joué un peu avec l'idée, voici ma page de test. Voir les résultats dans la console Firebug (F12). Je ne connais pas l'équivalent de console.clear() pour Chrome.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    <!doctype html>
    <html lang="fr">
    <head>
    	<meta charset="utf-8">
    	<meta name="Author" content="Daniel Hagnoul">
    	<title>Forum jQuery</title>
    	<link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Redressed&subset=latin&v2'>
    	<link rel="stylesheet" href="http://danielhagnoul.developpez.com/lib/jPicker/css/jPicker.dvjh-1.1.6.min.css" />
    	<style>
    		/* Base */
    		html { font-size:62.5%; } /* Pour 62.5% 1rem =~ 10px */
    		div,p,h1,h2,h3,h4,h5,h6,ul,ol,dl,form,table,img { margin:0; padding:0; }
    		body { background-color:rgb(122, 79, 79); color:#000000; font-family:sans-serif; font-size:1.4rem; font-style:normal; font-weight:normal; line-height:normal; letter-spacing:normal; }
    		h1,h2,h3,h4,h5 { font-family:'Redressed', cursive; padding:0.6rem; }
    		p, div, td { word-wrap:break-word; }
    		pre, code { white-space:pre-wrap; word-wrap:break-word; }
    		img, input, textarea, select { max-width:100%; }
            img { border:none; }
    		h1 { font-size:2.4rem; text-shadow: 0.4rem 0.4rem 0.4rem #bbbbbb; text-align:center; }
    		p { padding:0.6rem; }
    		.conteneur { width:95%; min-width:80rem; min-height:200rem; margin:1.2rem auto; background-color:#ffffff; color:#000000; border:0.1rem solid #666666; }
    		footer { margin-left:3.6rem; }
     
    		/* --- */
    		div { font-size:5rem; padding:0.6rem; margin-bottom:50rem; border:0.1rem dotted red; }
    	</style>
    </head>
    <body>	
    	<h1>Forum jQuery</h1>
    	<section class="conteneur">
    		<div id="toto">
    			<p>Je suis Toto ! Suis-je visible ?</p>
    		</div>
    		<div id="tata">
    			<p>Je suis Tata ! Suis-je visible ?</p>
    		</div>
    		<div id="titi">
    			<p>Je suis Titi ! Suis-je visible ?</p>
    		</div>
    		<div id="tutu">
    			<p>Je suis Tutu ! Suis-je visible ?</p>
    		</div>
    	</section>
    	<footer itemscope itemtype="http://danielhagnoul.developpez.com/">
    		<time datetime="2012-02-20T22:45:29.000+01:00" pubdate>2012-02-20T22:45:29.000+01:00</time>
    		<span itemprop="name">Daniel Hagnoul</span>
    		<a href="http://www.developpez.net/forums/u285162/danielhagnoul/" itemprop="url">@danielhagnoul</a>
    	</footer>
    	<script charset="utf-8" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    	<script charset="utf-8" src="http://danielhagnoul.developpez.com/lib/jPicker/jpicker-1.1.6.min.js"></script>
    	<script>
    		"use strict";
     
    		// Date ISO format long US
    		Date.prototype.formatISO = function(){
    			this._nowFormat = 'aaaa-mm-jjThh:ii:ss.000Szz:00';
    			this._toLen2 = function(_nowStr){
    				_nowStr = _nowStr.toString();
    				return ('0'+_nowStr).substr(-2,2);
    			};
    			this._nowFormat = this._nowFormat.replace(/j+/, this._toLen2(this.getDate()));
    			this._nowFormat = this._nowFormat.replace(/m+/, this._toLen2(this.getMonth()+1));
    			this._nowFormat = this._nowFormat.replace(/a+/, this.getFullYear());
    			this._nowFormat = this._nowFormat.replace(/h+/, this._toLen2(this.getHours()));
    			this._nowFormat = this._nowFormat.replace(/i+/, this._toLen2(this.getMinutes()));
    			this._nowFormat = this._nowFormat.replace(/s+/, this._toLen2(this.getSeconds()));
    			this._nowFormat = this._nowFormat.replace(/S+/, (this.getTimezoneOffset() < 0) ? ("+") : ("-"));
    			this._nowFormat = this._nowFormat.replace(/z+/, this._toLen2(Math.abs(this.getTimezoneOffset()/60)));
    			return this._nowFormat;
    		};
     
    		$(function(){
    			/* Base */
    			console.log(new Date().formatISO());
     
    			/* --- */
    var projets = [ "#toto", "#tata", "#titi", "#tutu" ],
    	projetsLength = projets.length;
     
    $( window ).scroll( function(){
    	// Firebug uniquement
    	console.clear();
     
    	for ( var i = 0; i < projetsLength; i++ ){
    		console.log( projets[i] + " est visible : " + checkvisible( projets[i] ) );
    	}
    });
     
    function checkvisible( elm ){
        var vpH = $( window ).height(), // Viewport Height
            st = $( window ).scrollTop(), // Scroll Top
            y = $( elm ).offset().top, // element top
    		h = $( elm ).outerHeight(); // element height
     
        return ( ( y + h > st ) && ( y - st < vpH ) );
    }
     
    			/*
    			 * jPicker : http://www.digitalmagicpro.com/jPicker/,
    			 * est un outil pour choisir rapidement une couleur
    			 *
    			 * Sue Firefox, avec Web Developper, cette version
    			 * de jPicker provoque des avertissements CSS !
    			 *
    			 * Mais il est très pratique !
    			 */
    			$.fn.jPicker.defaults.images.clientPath="http://danielhagnoul.developpez.com/lib/jPicker/images/";
     
    			$(".conteneur").jPicker({
    				window: {
    					expandable : true,
    					title : "jPicker : choissisez une couleur :",
    					alphaSupport : true,
    					position : {
    						x : 'screenCenter',
    						y : 'top'
    					}
    				},
    				color : {
    					active : new $.jPicker.Color({
    						r : 210,
    						g : 214,
    						b : 98,
    						a : 128
    					})
    				}
    			}, function( color, context ){
    				var c = color.val("all");
    				if ( c ){
    					$( "body" ).css( "background-color", "rgba(" + c.r + "," + c.g + "," + c.b + "," + (c.a/255).toFixed(2) + ")" );
    				}
    			});
    		});
    	</script>
    </body>  
    </html>

  5. #5
    Rédacteur

    Avatar de Bovino
    Homme Profil pro
    Développeur Web
    Inscrit en
    Juin 2008
    Messages
    23 647
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 53
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2008
    Messages : 23 647
    Points : 91 220
    Points
    91 220
    Billets dans le blog
    20
    Par défaut
    Citation Envoyé par fungio
    j'ai trouvé un forum américain
    Pourquoi aller si loin ?
    Savoir si un élément est visible à l'écran

Discussions similaires

  1. [JavaScript] [SRC] Savoir si un élément est visible à l'écran
    Par Bovino dans le forum Contribuez
    Réponses: 1
    Dernier message: 01/05/2014, 00h47
  2. Savoir si un element est onFocus
    Par Jonas7 dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 27/01/2010, 21h00
  3. Savoir si une image est visible
    Par pas30 dans le forum Général JavaScript
    Réponses: 6
    Dernier message: 13/01/2009, 16h41
  4. [Hibernate - HQL] Savoir si un element est racine
    Par eXiaNazaire dans le forum Langage SQL
    Réponses: 2
    Dernier message: 04/12/2007, 11h18
  5. Savoir si un JPane est visible
    Par julien1311 dans le forum AWT/Swing
    Réponses: 2
    Dernier message: 19/07/2007, 17h38

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo