Link in div repeats the function on roll over - javascript

So I have a side menu made of divs containing some text and a link.
When I roll over the div I fade in an image.
When I roll over the a tag link in that div it repeats that same function and creates another fade in of the same image witch looks real buggy.
How can I prevent the link a tag to repeat the function
I tried to create a variable set to true on roll over the link and a if inside the fade in method but with no success?
Any ideas would be appreciated.
$j=jQuery.noConflict();
jQuery(document).ready(function($) {
var num = 0;
var numtot = 4;
var delai = null;
var stop_x=0;
var numCur=0;
var thisIs = 0;
var delayRoll = 0;
var count = null;
var overlink = false;
//on ini
//--//
$j(document).ready(function() {
function start() {
delai=setInterval(test, 5000);
console.log(">> start interval");//>>>>>>>>>>>>>>>>>>>trace;
};
numtot = ($j("#news dl dt").size())-1;
test();
start();
})
function fistImage(){
//if(delayRoll==0){
$j("#news dl dd").fadeOut();
$j("#news dl dt").removeClass('current');
console.log("num on test: " + num);//>>>>>>>>>>>>>>>>>>>trace;
console.log("numCur on test: " + numCur);//>>>>>>>>>>>>>>>>>>>trace;
//console.log("current is"+ );//>>>>>>>>>>>>>>>>>>>trace;
$j("#news dl dt").eq(num).addClass('current');
$j("#news dl dt").eq(num).next('dd').fadeIn(500);
if (num>=numtot) {num = 0;} else {num ++;};
//}
}
//firstImage();
//--//
////////--------//////// NEXT IMAGE METHOD
function nextImage(){
if( overlink == false || overlink == true){
console.log("delayRoll image: " + delayRoll);//>>>>>>>>>>>>>>>>>>>trace;
$j("#news dl dd").fadeOut();
$j("#news dl dt").removeClass('current');
$j(thisIs).addClass('current');
$j(thisIs).next('dd').fadeIn(500);
//stop_x=1;
var new_pos=$j(thisIs).attr('id').substring(4, 5);
new_pos=parseInt(new_pos);
if (numtot==new_pos) {new_pos = 0;}
num = new_pos;
numtot = ($j("#news dl dt").size())-1;
}
}
//--//
function test() {
//console.log("num on test: " + num);//>>>>>>>>>>>>>>>>>>>trace;
if(stop_x==0){
fistImage();
}
if(stop_x==1){
}};
//--//
//--/
delai=setInterval(test, 5000);
//--//
//-- OVERLAY//
$j(".overlay").mouseover(function() {
stop_x=1;
}).mouseout( function (){
stop_x=0;
});
//--//mouseover
$j("#news dl dt").mouseover(function() {
thisIs = $j(this);
stop_x=1;
clearInterval(delai);
nextImage();
delayRoll==2;
})
$j("#news dl dt").mouseout(function() {
stop_x==0;
firstImage();
delayRoll=0;
})
$("#news dl dt a").live("mouseover mouseout", function() {
// alert(this.href);
//return false;
overlink=true;
});
})//close duc ready
//--//
and here the html
<div id="news" class="slideshow">
<dl>
<dt id="pos_1">08/16/11<br /><br />Holy Cross to Welcome Class of 2015 on Aug. 27<br />
<a class="more" href="blog/2011/08/16/holy-cross-to-welcome-class-of-2015-on-aug-27/index.html">See more ></a>
</dt>
<dd>
<div class="overlay">
<p>Holy Cross to Welcome Class of 2015 on Aug. 27 <span class="nav">
<img src="wp-content/themes/marsten/images/ico_more_white.png" width="14" height="14" alt="" />
<div id="disLink"><span><a class="more" href="blog/2011/08/16/holy-cross-to-welcome-class-of-2015-on-aug-27/index.html" >See more ></a></span></div>
</span>
</p>
<div id="boxit"><p class="author">by
Nikolas Markantonatos</p></div>
</div>
<img alt="" src="wp-content/uploads/2011/08/gate2.jpg" width="612" height="451" />
</dd>

Trying doing a event.stopPropagation during the hover over after you fade in...

Related

How can I reduce the repetitive work of this jquery source?

$("#sel1").click(function () {
$("#itemed1").attr("src", "../img/tab_img_01_on.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
$("#itemed2").attr("src", "../img/tab_img_02_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
$("#itemed3").attr("src", "../img/tab_img_03_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed4").attr("src", "../img/tab_img_04.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
$("#itemed4").attr("src", "../img/tab_img_04_on.png");
$("#itemed1").attr("src", "../img/tab_img_01.png");
$("#itemed2").attr("src", "../img/tab_img_02.png");
$("#itemed3").attr("src", "../img/tab_img_03.png");
$(this).find("span").addClass("add");
$("#sel1").find("span").removeClass("add");
$("#sel2").find("span").removeClass("add");
$("#sel3").find("span").removeClass("add");
});
Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?
You could use a simple combination of selectors.
See sample here or in CodePen:
$(".selector").click(function () {
let index = $(this).data('index');
$(".selector").find("span").removeClass("add");
$(this).find("span").addClass("add");
$(".imgs").each( function(){
$(this).attr("src", `../img/tab_img_0${$(this).data('index')}.png`);
});
$(`.imgs[data-index="${index}"]`).attr("src", `../img/tab_img_0${index}_on.png`);
});
.add {
font-size: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="selector" data-index="1">Sel 1 <span>sample</span></button>
<button class="selector" data-index="2">Sel 2 <span>sample</span></button>
<button class="selector" data-index="3">Sel 3 <span>sample</span></button>
<button class="selector" data-index="4">Sel 4 <span>sample</span></button>
<img data-index="1" class="imgs" />
<img data-index="2" class="imgs" />
<img data-index="3" class="imgs" />
<img data-index="4" class="imgs" />
Obviously, if you are using n index > 10 you should use the padStart function.
Expendable version of same code.
function pad(v) {
return (v.length === 2 ? v : '0' + v);
}
$('[id^=sel]').click(function() {
var total = 4;
var idNumber = $(this).attr('id').match(/\d+/);
for ( i = 1; i <= total; i++ ) {
$('#itemed' + i).attr('src', '../img/tab_img_' + pad(i) + '.png');
$('#sel' + i).find('span').removeClass('add');
}
$('#itemed' + idNumber).attr('src', '../img/tab_img_' + pad(idNumber) + '_on.png');
$(this).find('span').addClass('add');
});
But I think #SnakeDrak approach is correct
This will work up to selects with the number 9. It will need a little more work to make it work with numbers grater then 9
$("[id^=sel]").click(function () { // match every element where the id starts with "sel"
var idNumber = $(this).attr('id').match(/\d+/); // get the number of given id
// reset all src paths from all given elements
$("#itemed1, #itemed2, #itemed3, #itemed4").attr("src", "../img/tab_img_01.png");
// use the idNumber to concatenate the selector and set the src
$("#itemed" + idNumber).attr("src", "../img/tab_img_0"+idNumber+"_on.png");
// remove the add class to all given elements
$("#sel1, #sel2, #sel3, #sel4").find("span").removeClass("add");
// add the "add" class to $(this) element
$(this).find("span").addClass("add");
});
Please refer below code.
$("[id^=sel]").on('click', function() {
var selectionID = ["sel1", "sel2", "sel3", "sel4"];
var itemID = ["itemed1", "itemed2", "itemed3", "itemed4"];
var selectedButton = $(this).attr("value");
$(this).find("span").addClass("add");
var indexID = selectionID.indexOf(selectedButton) + 1;
$("#itemed" + indexID).attr("src", "../img/tab_img_0" + indexID + "_on.png");
selectionID = selectionID.filter(e => e !== selectedButton);
itemID = itemID.filter(e => e !== itemID[indexID - 1]);
for (var i = 0; i < selectionID.length; i++) {
$("#" + selectionID[i]).find("span").removeClass("add");
$("#" + itemID[i]).attr("src", "../img/tab_img_0" + itemID[i].charAt(itemID[i].length - 1) + ".png");
}
});
.add {
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button value="sel1" id="sel1"><span>sel1</span></button><br/>
<button value="sel2" id="sel2"><span>sel2</span></button><br/>
<button value="sel3" id="sel3"><span>sel3</span></button><br/>
<button value="sel4" id="sel4"><span>sel4</span></button><br/>
<img src="" id="itemed1">
<img src="" id="itemed2">
<img src="" id="itemed3">
<img src="" id="itemed4">

Trying to get my imageslider to work

I have an image slider that shows all the images I have in my view in MVC5 however when I reach the last one I dont know how to make it jump back to the first one and continue from there.
The Html for the thing looks like this:
<div class="container2">
<div class="slider_wrapper">
<ul id="image_slider">
<li> <img src="#Model.ImagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"],"../../")" width=50 height=50 /> </li>
#foreach (var item in Model.ImageGallarys)
{
<li> <img src="#item.ImagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"],"../../")" width=50 height=50 /></li>
}
</ul>
<span class="nvgt" id="prev"></span>
<span class="nvgt" id="next"></span>
</div>
</div>
And the javascript looks like this:
function startFunction() {
$(window).load(function () {
var src = $("#image_slider").find('li:first-child img').attr('src');
$("#image_slider li:first-child ").addClass("start");
var src1 = src.replace("../..", " ");
var src2 = src1.replace('\\', "/");
$(".container2").css("background-image", 'url("' + src2 + '")');
//fadeInandOut();
});
}
function nextImageFunction() {
$("#next").click(function () {
$("li.start").next("li").addClass("start");
$("li.start").prev("li").removeClass();
var srcNext = $("li.start img").attr('src');
var srcNext1 = srcNext.replace("../..", " ");
var srcNext2 = srcNext1.replace('\\', "/");
$(".container2").css("background-image", 'url("' + srcNext2 + '")');
if($("li.start").is(":last-child"))
{
//I want the solution for this one!
}
});
}
function previousImageFunction() {
$("#prev").click(function () {
$("li.start").prev("li").addClass("start");
$("li.start").next("li").removeClass();
var srcNext = $("li.start img").attr('src');
var srcNext1 = srcNext.replace("../..", " ");
var srcNext2 = srcNext1.replace('\\', "/");
$(".container2").css("background-image", 'url("' + srcNext2 + '")');
});
if ($("li.start").is(":first-child")) {
//And also for this one!
}
}
Help me Obiwan Kenobi your my only hope!
Just do it :)
<div class="container2">
<div class="slider_wrapper">
<ul id="image_slider">
<li> <img src="#Model.ImagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"],"../../")" width=50 height=50 /> </li>
#foreach (var item in Model.ImageGallarys) {
<li> <img src="#item.ImagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"],"../../")" width=50 height=50 /></li>
}
</ul>
<span class="nvgt" id="prev"></span>
<span class="nvgt" id="next"></span>
</div>
</div>
And in our JS (with a little refoctoring) we will have:
// we need this support principle don't repeat yourself (DRY)
function avoidSrcSymbols(src){
return src.replace("../..", " ").src1.replace('\\', "/");
}
// This function need to improve set image via class in future//
function changeImage($src, imageSrc){
$src.css("background-image", 'url("' + imageSrc + '")');
}
function startFunction() {
$(window).load(function () {
var $firstLi = $("#image_slider").find('li:first-child');
$firstLi.addClass("start");
var src = $firstLi.find('img').attr('src');
src = avoidSrcSymbols(src);
changeImage($(".container2"), src);
//fadeInandOut();
});
}
function nextLi($currentLi){
if ($currentLi.is(":last-child")) {
// here is many method to get firstChild from current
return $currentLi.parent().first();
}
return $currentLi.next("li");
}
function prevLi($currentLi){
if ($currentLi.is(":first-child")) {
// here is many method to get lastChild from current
return $currentLi.parent().last();
}
return $currentLi.prev("li");
}
function nextImageFunction() {
$("#next").click(function () {
var $currentLy = $("li.start");
nextLi($currentLy).addClass("start");
$currentLy.removeClass("start");
var src = $currentLy.find("img").attr('src');
src = avoidSrcSymbols(src);
changeImage($(".container2"), src);
});
}
function previousImageFunction() {
$("#prev").click(function () {
var $currentLy = $("li.start");
prevLi($currentLy).addClass("start");
$currentLy.removeClass("start"); // remove Class from currect li
var src = $currentLy.find("img").attr('src');
src = avoidSrcSymbols(src);
changeImage($(".container2"), src);
});
}

hide slider carousel button when there are no more elements with bootstrap

Good morning!!
I need to block the arrow on the left or hide the date and only use the right if there elements. One time you use the right arrow "because there were more hidden elements" and this has no more elements desahibilitarla not slide to keep doing the right arrow. The left arrow to return to the top dwell. As is possible with bootstrap or javascript? Please help!!! :(
enter image description here
<%
// final List<String> articlesMarkup = ContentListWebContexts.getArticlesMarkup(renderRequest);
final List<String> articlesMarkupPrestatges = ContentListWebContexts.getArticlesMarkup(renderRequest);
final ContentListPreferences prefs = ContentListWebContexts.getContentListPrefs(renderRequest);
final String viewAllFullFriendlyUrl = prefs.getViewAllPageFullUrl(themeDisplay);
// pageContext.setAttribute( "articlesMarkup", articlesMarkup );
pageContext.setAttribute( "articlesMarkupPrestatges", articlesMarkupPrestatges );
pageContext.setAttribute( "viewAllFullFriendlyUrl", viewAllFullFriendlyUrl);
%>
<%-- Vista, propiamente dicha --%>
<c:choose>
<c:when test="${empty articlesMarkupPrestatges}">
<p><liferay-ui:message key="contentlist.view.noarticles" /></p>
</c:when>
<c:otherwise>
<%
// String friendlyURL = themeDisplay.getLayout().getFriendlyURL();
// String currentUrl = URLDecoder.decode(themeDisplay.getURLCurrent(),"UTF-8");
// String homeUrl = themeDisplay.getURLHome();
// int startIndex = 1;
%>
<div class="seccionTitular margenSup">
<h1 class="two">
<!-- <div class="masInfoTitular"></div> -->
<span><liferay-ui:message key="contentlist.view.title.prestatges" /></span>
<div class="rayaTitularPrestatges pull-left"></div>
<div class="rayaTitularPrestatges pull-right"></div>
</h1>
</div>
<div class="wrapper-prestatges rowPrestatges">
<div class="jcarousel-wrapper-prestatges">
<div class="jcarousel-prestatges">
<ul id="ulPrestatges">
<c:forEach var="articleMarkupPrestatges" items="${articlesMarkupPrestatges}" varStatus="loop">
<li>${articleMarkupPrestatges}</li>
</c:forEach>
</ul>
</div>
<span class="glyphicon glyphicon-menu-left" aria-hidden="true"></span> <span class="sr-only">Previous</span>
<span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span> <span class="sr-only">Next</span>
<!-- <p class="jcarousel-pagination-prestatges"></p> -->
</div>
</div>
<script type="text/javascript">
(function($) {
$(function() {
var jcarousel = $('.jcarousel-prestatges');
var perPageValue = $(this);
jcarousel
.on('jcarousel:reload jcarousel:create', function () {
var carouselPrestatges = $(this);
var widthWindow = window.innerWidth;
carouselPrestatges.css('width', '100%');
var widthCarouselPrestatges = carouselPrestatges.innerWidth();
carouselPrestatges.css('width', widthCarouselPrestatges + 'px');
if (widthWindow >= 1200) {
widthCarouselPrestatges = widthCarouselPrestatges / 7;
perPageValue = 7;
} else if (widthWindow >= 992) {
widthCarouselPrestatges = widthCarouselPrestatges / 5;
perPageValue = 5;
} else if (widthWindow >= 768) {
widthCarouselPrestatges = widthCarouselPrestatges / 3;
perPageValue = 3;
} else {
perPageValue = 1;
}
carouselPrestatges.jcarousel('items').css('width', Math.ceil(widthCarouselPrestatges) + 'px');
$('#ulPrestatges').css('width', '20000em');
$('.jcarousel-control-prev-prestatges')
.jcarouselControl({
target: '-=' + perPageValue
});
$('.jcarousel-control-next-prestatges')
.jcarouselControl({
target: '+=' + perPageValue
});
$('.jcarousel-pagination-prestatges')
.on('jcarouselpagination:active', 'a', function() {
$(this).addClass('active');
})
.on('jcarouselpagination:inactive', 'a', function() {
$(this).removeClass('active');
})
.on('click', function(e) {
e.preventDefault();
})
.jcarouselPagination({
perPage: perPageValue,
item: function(page) {
return '' + page + '';
}
});
})
.jcarousel({
wrap: null,
});
});
})(jqCarrusel);
var left = $('.jcarousel-prestatges ul').css('left');
var posicion = "inicio"; // podria ser necesaria?
$('.jcarousel-control-prev-prestatges')
.click(function () {
left = $('.jcarousel-prestatges ul').css('left');
if (left == "0px" || left == "auto") {
$('.jcarousel-control-prev-prestatges').addClass('pruebaAddClass');
} else {
$('.jcarousel-control-prev-prestatges').removeClass('pruebaAddClass');
$('.jcarousel-control-prev-prestatges').addClass('aaa');
};
});
$('.jcarousel-control-next-prestatges')
.click(function () {
left = $('.jcarousel-prestatges ul').css('left');
if (left == "0px" || left == "auto") {
$('.jcarousel-control-prev-prestatges').addClass('avanzaAddClass');
$('.jcarousel-control-prev-prestatges').removeClass('pruebaAddClass');
};
});
</script>
</c:otherwise>
</c:choose>
I believe this could be considered a duplicate question (especially since OP for this question also had multiple carousels): bootstrap carousel hide controls on first and last
However, with a little bit of searching on both SO and the internet, I was able to find an outstanding blog post (also referenced by Fred K) that does a great job explaining this.

Javascript function not working for all elements

I'm trying to write a script which changes image on mouse hover. I have 6 images, but the function is working for only one of them (the first one)
<div id="picture-container">
<img class="picture" id="360" src="360.jpg" onclick="enlarge(360);" onmouseover="pic_info(360);"
onmouseout="pic_ret(360);"/>
<img class="picture" id="bmx" src="bmx.jpg" onclick="enlarge(bmx);"/>
<img class="picture" id="buzludzha" src="buzludzha.jpg" onclick="enlarge(buzludzha);"
onmouseover="pic_info(buzludzha);"/>
<img class="picture" id="pirata" src="pirata.jpg" onclick="enlarge(pirata);"
onmouseover="pic_info(pirata);"/>
<img class="picture" id="snowboard" src="snowboard.jpg" onclick="enlarge(snowboard);"
onmouseover="pic_info(snowboard);"/>
<img class="picture" id="vitiskali" src="vitiskali.jpg" onclick="enlarge(vitiskali);"
onmouseover="pic_info(vitiskali);"/>
<img class="picture" id="ispolin" src="ispolin.jpg" onclick="enlarge(ispolin);"
onmouseover="pic_info(ispolin);"/>
</div>
And the script:
function pic_info(id) {
if (id == "360") {
var p = document.getElementById(id);
p.src = "360info.jpg";
}
if (id == "buzludzha") {
var p = document.getElementById(id);
p.src = "buzludzhainfo.jpg";
}
if (id == "pirata") {
var p = document.getElementById(id);
p.src = "piratainfo.jpg";
}
if (id == "snowboard") {
var p = document.getElementById(id);
p.src = "snowboardinfo.jpg";
}
if (id == "vitiskali") {
var p = document.getElementById(id);
p.src = "vitiskaliinfo.jpg";
}
if (id == "ispolin") {
var p = document.getElementById(id);
p.src = "ispolininfo.jpg";
}
As I said the script works only for picture with id="360" and it is imported in the head tag of the html document.The same thing happens with the function "enlarge();". Why is that and how can I fix it?
Thank you, in advance!
just to scratch the surface, are passing a variable instead of a string : enlarge(bmx); should be : enlarge('bmx');, and so on for the others

Hiding/Showing Div Elements

This should cycle through the <div> tags, but it isn't even showing the first one. It should show a "0", then 50ms later, show "1", then "2", and then "3". I get nothing.
Here's the HTML:
<div class="header" id="animation">
<div id="aniObj0" style="display: none;" onLoad="runAnimation();">0</div>
<div id="aniObj1" style="display: none;">1</div>
<div id="aniObj2" style="display: none;">2</div>
<div id="aniObj3" style="display: none;">3</div>
</div>
The JavaScript:
var aniNum = 0;
var animationDelay = 50;
var frameDelay = 50;
function runAnimation()
{
Console.log("runningAnimation");
var prevObj = document.getElementById('aniObj' + (aniNum - 1));
var aniObj = document.getElementById('aniObj' + aniNum);
if(aniObj != null){
if(prevObj != null){
aniObj.style.display = 'none;';
}
aniObj.style.display = 'block;';
aniNum++;
if(aniNum == 0){
setTimeout("runAnimation();", animationDelay);
}else{
setTimeout("runAnimation();", frameDelay);
}
}else{
aniNum = 0;
newAnimation();
}
}
You're very close. See code below (and comments in code).
HTML:
<div class="header" id="animation">
<!-- Removed onload="runAnimation()" - onload doesn't exist for a div -->
<div id="aniObj0" style="display: none;">0</div>
<div id="aniObj1" style="display: none;">1</div>
<div id="aniObj2" style="display: none;">2</div>
<div id="aniObj3" style="display: none;">3</div>
</div>
JavaScript:
var aniNum = 0;
var animationDelay = 500; //Changed to 500ms to you could see better
var frameDelay = 500; //Changed to 500ms to you could see better
function runAnimation()
{
var prevObj = document.getElementById('aniObj' + (aniNum - 1));
var aniObj = document.getElementById('aniObj' + aniNum);
if (aniObj != null) {
if (prevObj != null) {
aniObj.style.display = 'none;';
}
aniObj.style.display = '';
aniNum++;
if (aniNum == 0) {
//Changed setTimeout("runAnimation()", animationDelay); to
//setTimeout(runAnimation, animationDelay);
setTimeout(runAnimation, animationDelay);
} else {
setTimeout(runAnimation, frameDelay);
}
} else {
aniNum = 0;
newAnimation();
}
}
//You need to place this in a valid event. onload event of the body maybe?
runAnimation();
Here's a working fiddle.

Categories