Duplicate <div> without duplicating Javascript

Asked

Viewed 343 times

0

I need the following help: I managed to join two codes I found on the internet, and edited the formatting to my liking.

I have a gallery with images and overflow horizontal, my code works, but I need to repeat the full div once or more times on the site, and as I am layman in the area, I can not solve without conflict, I tried to create two names and scripts and css for everything, but gave many code conflicts and the semantics turned horrible, I know it is possible to create more than one with small help in the code, but I came to the conclusion that without help I will not find the answer!

How are you: inserir a descrição da imagem aqui

How I need: inserir a descrição da imagem aqui

Code:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function mostra(theId){
    var theArray= new Array('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8');
    for(i=0; i<theArray.length; i++){
        if(theArray[i] == theId){
            document.getElementById(theId).style.display='block';
        }else{
            document.getElementById(theArray[i]).style.display='none';
        }
    }
}
</script>
<script>
var SETTINGS = {
    navBarTravelling: false,
    navBarTravelDirection: "",
    navBarTravelDistance: 150
}

var colours = {
    0: "#00BAFF",
    1: "#32CD32",
    2: "#ECBB0C",
    3: "#40FEFF",
    4: "#14CC99",
    5: "#0082B2",
    6: "#7F4200",
    7: "#B25D7A",
    8: "#006B49",
    9: "#FF3400",
    10: "#00B27A",
    11: "#996B3D",
    12: "#CC7014",
    13: "#40FF8C",
    14: "#253A93",
    15: "#ECBB5E",
    16: "#125FB9",
    17: "#B9D912",
    18: "#99813D",
    19: "#867100",
}

document.documentElement.classList.remove("no-js");
document.documentElement.classList.add("js");

// Out advancer buttons

// the indicator
var pnIndicator = document.getElementById("pnIndicator");

var pnProductNav = document.getElementById("pnProductNav");
var pnProductNavContents = document.getElementById("pnProductNavContents");

pnProductNav.setAttribute("data-overflowing", determineOverflow(pnProductNavContents, pnProductNav));


// Set the indicator
moveIndicator(pnProductNav.querySelector("[aria-selected=\"true\"]"), colours[0]);

// Handle the scroll of the horizontal container
var last_known_scroll_position = 0;
var ticking = false;

function doSomething(scroll_pos) {
    pnProductNav.setAttribute("data-overflowing", determineOverflow(pnProductNavContents, pnProductNav));
}

pnProductNav.addEventListener("scroll", function() {
    last_known_scroll_position = window.scrollY;
    if (!ticking) {
        window.requestAnimationFrame(function() {
            doSomething(last_known_scroll_position);
            ticking = false;
        });
    }
    ticking = true;
});

pnProductNavContents.addEventListener(
    "transitionend",
    function() {
        // get the value of the transform, apply that to the current scroll position (so get the scroll pos first) and then remove the transform
        var styleOfTransform = window.getComputedStyle(pnProductNavContents, null);
        var tr = styleOfTransform.getPropertyValue("-webkit-transform") || styleOfTransform.getPropertyValue("transform");
        // If there is no transition we want to default to 0 and not null
        var amount = Math.abs(parseInt(tr.split(",")[4]) || 0);
        pnProductNavContents.style.transform = "none";
        pnProductNavContents.classList.add("pn-ProductNav_Contents-no-transition");
        // Now lets set the scroll position
        if (SETTINGS.navBarTravelDirection === "left") {
            pnProductNav.scrollLeft = pnProductNav.scrollLeft - amount;
        } else {
            pnProductNav.scrollLeft = pnProductNav.scrollLeft + amount;
        }
        SETTINGS.navBarTravelling = false;
    },
    false
);

// Handle setting the currently active link
pnProductNavContents.addEventListener("click", function(e) {
	var links = [].slice.call(document.querySelectorAll(".pn-ProductNav_Link"));
	links.forEach(function(item) {
		item.setAttribute("aria-selected", "false");
	})
	e.target.setAttribute("aria-selected", "true");
	// Pass the clicked item and it's colour to the move indicator function
	moveIndicator(e.target, colours[links.indexOf(e.target)]);
});

// var count = 0;
function moveIndicator(item, color) {
    var textPosition = item.getBoundingClientRect();
    var container = pnProductNavContents.getBoundingClientRect().left;
    var distance = textPosition.left - container;
	 var scroll = pnProductNavContents.scrollLeft;
    pnIndicator.style.transform = "translateX(" + (distance + scroll) + "px) scaleX(" + textPosition.width * 0.01 + ")";
	// count = count += 100;
	// pnIndicator.style.transform = "translateX(" + count + "px)";
	
    if (color) {
        pnIndicator.style.backgroundColor = color;
    }
}

function determineOverflow(content, container) {
    var containerMetrics = container.getBoundingClientRect();
    var containerMetricsRight = Math.floor(containerMetrics.right);
    var containerMetricsLeft = Math.floor(containerMetrics.left);
    var contentMetrics = content.getBoundingClientRect();
    var contentMetricsRight = Math.floor(contentMetrics.right);
    var contentMetricsLeft = Math.floor(contentMetrics.left);
	 if (containerMetricsLeft > contentMetricsLeft && containerMetricsRight < contentMetricsRight) {
        return "both";
    } else if (contentMetricsLeft < containerMetricsLeft) {
        return "left";
    } else if (contentMetricsRight > containerMetricsRight) {
        return "right";
    } else {
        return "none";
    }
}
</script>
* {
	box-sizing: inherit;
}

.pn-ProductNav_Wrapper {
	position: relative;
	padding: 0 11px;
	box-sizing: border-box;
}

.pn-ProductNav {
    /* Make this scrollable when needed */
    overflow-x: auto;
    /* We don't want vertical scrolling */
    overflow-y: hidden;
    /* For WebKit implementations, provide inertia scrolling */
    -webkit-overflow-scrolling: touch;
    /* We don't want internal inline elements to wrap */
    white-space: nowrap;
    /* If JS present, let's hide the default scrollbar */
    .js & {
        /* Make an auto-hiding scroller for the 3 people using a IE */
        -ms-overflow-style: -ms-autohiding-scrollbar;
        /* Remove the default scrollbar for WebKit implementations */
        &::-webkit-scrollbar {
            display: none;
        }
    }
	/* positioning context for advancers */
	position: relative;
	/*Crush the whitespace here*/
	font-size: 0;
}

.pn-ProductNav_Contents {
	float: left;
	transition: transform .2s ease-in-out;
	position: relative;
}

.pn-ProductNav_Contents-no-transition {
	transition: none;
}

.pn-ProductNav_Link {
	text-decoration: none;
	color: #888;
	/*Reset the font size*/
	font-size: 1.2rem;
	font-family: -apple-system, sans-serif;
	display: inline-flex;
	align-items: center;
	min-height: 44px;
	border: 1px solid transparent;
	padding: 0 11px;
	& + & {
		border-left-color: #eee;
	}
	&[aria-selected="true"] {
		color: #111;
	}
}

.pn-ProductNav_Indicator {
	position: absolute;
	bottom: 0;
	left: 0;
	height: 4px;
	width: 100px;
	background-color: transparent;
	transform-origin: 0 0;
	transition: transform .2s ease-in-out, background-color .2s ease-in-out;
}


#caixas{
	flex-direction: row;
	justify-content: center;
	align-items: center;
	width: 100%;
	margin-top: 10px;
		
}
.conteudocaixas{
	overflow-x: scroll;
	overflow-y: hidden;
	white-space: nowrap;
}
.imagemcaixas{
	margin-top: 5px;
	width: 12.15%;
	max-width: 170px;
	height: auto;
	display: inline-block;
}
.position_btcx{
	display: inline-block;
}
.button_cx{
	background: #fff;
	height: 30px;
	width: 30px;
	border: 1px solid #000;
	border-radius: 5px;
}
		
.caixa1{
	margin: 0 0.5% 0 0.5%;
}
.caixa2{
	margin: 0 0.5% 0 0.5%;
}
  
<div id="caixas">
    <div class="caixa1">
        <div class="pn-ProductNav_Wrapper">
            <nav id="pnProductNav" class="pn-ProductNav">
                <div id="pnProductNavContents" class="pn-ProductNav_Contents">
                    <a onclick="mostra('item1');" style="cursor: hand;" href="#" class="pn-ProductNav_Link" aria-selected="true">Galeria1</a>
                    <a onclick="mostra('item2');" style="cursor: hand;" href="#" class="pn-ProductNav_Link">Galeria2</a>
                    <a onclick="mostra('item3');" style="cursor: hand;" href="#" class="pn-ProductNav_Link">Galeria3</a>
                    <span id="pnIndicator" class="pn-ProductNav_Indicator"></span>
                </div>
            </nav>

            <div id="item1" style="display:block;">
                <div class="conteudocaixas">
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                </div>
            </div>

            <div id="item2" style="display:none;">
                <div class="conteudocaixas">
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                </div>
            </div>

            <div id="item3" style="display:none;">
                <div class="conteudocaixas">
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                </div>
            </div>

        </div>
    </div>
</div>

1 answer

1


I simplified your code, and used only one command on Jquery, that I saw was included in your code.

First the code Javascript, forget all those functions, just use this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    document.documentElement.classList.remove("no-js");
    document.documentElement.classList.add("js");

    $('.pn-ProductNav_Link').click(function() {
        // Remove a class active, de todos os itens do menu clicado
        $(this).parent().children().removeClass('active');

        // Adiciona a classe active, a esse menu clicado
        $(this).addClass('active');

        // Deixa invisível todos as seções de fotos dessa área
        $(this).parent().parent().parent().children("[item]").css('display', 'none');

        // Torna visível somente a área que tem o mesmo ID do item clicado
        $(this).parent().parent().parent().children("[item='" + $(this).attr('item') + "']").css('display', 'block');
    });
</script>

Then the CSS, I changed a few things. The main change was to realize that effect of the line below the selected menu. I created a class active, rather than creating an element. This class handles the borders of the item a selected, already with the transition effects via CSS.

<style>
    * {
        box-sizing: inherit;
    }
    .pn-ProductNav_Wrapper {
        position: relative;
        padding: 0 11px;
        box-sizing: border-box;
    }
    .pn-ProductNav {
        /* Make this scrollable when needed */
        overflow-x: auto;
        /* We don't want vertical scrolling */
        overflow-y: hidden;
        /* For WebKit implementations, provide inertia scrolling */
        -webkit-overflow-scrolling: touch;
        /* We don't want internal inline elements to wrap */
        white-space: nowrap;
        /* If JS present, let's hide the default scrollbar */
        .js & {
            /* Make an auto-hiding scroller for the 3 people using a IE */
            -ms-overflow-style: -ms-autohiding-scrollbar;
            /* Remove the default scrollbar for WebKit implementations */
            &::-webkit-scrollbar {
                display: none;
            }
        }
        /* positioning context for advancers */
        position: relative;
        /*Crush the whitespace here*/
        font-size: 0;
        height: 46px;
    }
    .pn-ProductNav_Contents {
        float: left;
        transition: transform .2s ease-in-out;
        position: relative;
    }
    .pn-ProductNav_Contents-no-transition {
        transition: none;
    }
    .pn-ProductNav_Link {
        text-decoration: none;
        color: #888;
        /*Reset the font size*/
        font-size: 1.2rem;
        font-family: -apple-system, sans-serif;
        display: inline-flex;
        align-items: center;
        min-height: 44px;
        padding: 0 11px;
        & + & {
            border-left-color: #eee;
        }
        &[aria-selected="true"] {
            color: #111;
        }
    }
    .pn-ProductNav_Link.active {
        border-bottom: 4px solid;
        border-bottom-color: rgb(0, 186, 255);
        transition: border .2s ease-in-out;
    }
    caixas{
        flex-direction: row;
        justify-content: center;
        align-items: center;
        width: 100%;
        margin-top: 10px;

    }
    .conteudocaixas{
        overflow-x: scroll;
        overflow-y: hidden;
        white-space: nowrap;
    }
    .imagemcaixas{
        margin-top: 5px;
        width: 12.15%;
        max-width: 170px;
        height: auto;
        display: inline-block;
    }
    .position_btcx{
        display: inline-block;
    }
    .button_cx{
        background: #fff;
        height: 30px;
        width: 30px;
        border: 1px solid #000;
        border-radius: 5px;
    }
    .caixa{
        margin: 0 0.5% 0 0.5%;
    }
</style>

Finally the HTML. I removed the replay of the images to save space here. It would look like this:

<div class="caixas">
    <div class="caixa">
        <div class="pn-ProductNav_Wrapper">
            <nav class="pn-ProductNav">
                <div class="pn-ProductNav_Contents">
                    <a item="1" style="cursor: hand;" href="#" class="pn-ProductNav_Link active">Galeria1</a>
                    <a item="2" style="cursor: hand;" href="#" class="pn-ProductNav_Link">Galeria2</a>
                    <a item="3" style="cursor: hand;" href="#" class="pn-ProductNav_Link">Galeria3</a>
                </div>
            </nav>

            <div item="1" style="display:block;">
                <div class="conteudocaixas">
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                </div>
            </div>

            <div item="2" style="display:none;">
                <div class="conteudocaixas">
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                </div>
            </div>

            <div item="3" style="display:none;">
                <div class="conteudocaixas">
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                </div>
            </div>
        </div>
    </div>
    <div class="caixa">
        <div class="pn-ProductNav_Wrapper">
            <nav class="pn-ProductNav">
                <div class="pn-ProductNav_Contents">
                    <a item="1" style="cursor: hand;" href="#" class="pn-ProductNav_Link active">Galeria1</a>
                    <a item="2" style="cursor: hand;" href="#" class="pn-ProductNav_Link">Galeria2</a>
                    <a item="3" style="cursor: hand;" href="#" class="pn-ProductNav_Link">Galeria3</a>
                </div>
            </nav>

            <div item="1" style="display:block;">
                <div class="conteudocaixas">
                    <a href="#"><img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver10_xlg.jpg" alt="#"/></a>
                </div>
            </div>

            <div item="2" style="display:none;">
                <div class="conteudocaixas">
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver11_xlg.jpg" alt="#"/>
                </div>
            </div>

            <div item="3" style="display:none;">
                <div class="conteudocaixas">
                    <img class="imagemcaixas" src="http://cdn.cinepop.com.br/2017/06/spiderman_homecoming_ver12_xlg.jpg" alt="#"/>
                </div>
            </div>
        </div>
    </div>
</div>

In general, I have arranged for the manipulation to refer to the clicked element and not to IDs. The HTML tag ID assumes that the element is unique, which in your case is not true. Thus using classes, logic is applied homogeneously to all elements and possible duplicates. Not to mention the simplicity of the applied programming to solve the problem. The section is located through a custom attribute created in HTML, the attribute item. The âncora clicked and the div share the same value, thus linking one another.

Final result:

Imagem de Resultado Final

  • Man, to be perfect just missed the underlining effect running and changing color, but already helped me a lot!

  • 1

    What would that effect look like? Because the underscore changes from one to the other. And the color would be random?

  • The effect causes when changing tab the line does not disappear from one and appears in the other, it runs from one to the other. .

  • If you could help me I would appreciate it, the effect I got here: http://jsfiddle.net/xY7tx/4845/

  • Another simpler, effect is only in css, but as Hover. link: https://codepen.io/rm/pen/ldhon

Browser other questions tagged

You are not signed in. Login or sign up in order to post.