Creating a javascript variable that adds 1 when an event happens - javascript

Context: I'm helping my friend create a political joke sort of website.
I need it to add 1 to a variable every time the onmouseover event is triggered.
<img src="tm.png" onmouseover='this.src="jc.png"'>
I have this so far but I need to find a way to link it with a function that will add 1 to itself when that event happens. I have multiple onmouseover events around the page so I need it to work for them all. I know how to make the variable but I am unsure on how to add 1 each time the onmouseover event happens, I am also unsure on how to add the function to the onmouseover event. Thanks

hoverCounter = 0;
<img src="http://www.darbsterkitty.com/uploads/5/5/5/6/55568079/b8sk1f_orig.jpg" height="200px" onmouseover="hoverCounter++; console.log('hoverCounter: ' + hoverCounter)"></img>

Use event delegation and check whether the hovered element is an image.
var count = 0;
addEventListener("mouseover", function(e){
if(e.target.tagName == "IMG"){
count++;
}
console.log(count);
})
<img src="http://lorempixel.com/50/50?0"/>
<img src="http://lorempixel.com/50/50?1"/>

<img id="someImage1" src="http://via.placeholder.com/350x150" >
<img id="someImage2" src="http://via.placeholder.com/350x150" >
<br/>
Hover Count:
<input id="countDisplay" type="text"/>
JS:
// Initial count
var hoverCount = 0;
// Function to increment
function onHovered(event){
hoverCount++;
document.getElementById('countDisplay').value = hoverCount;
}
// Bind events
document.getElementById('someImage1').onmouseover = onHovered;
document.getElementById('someImage2').onmouseover = onHovered;

Related

Link or button sets a variable, then calls the script

I have a script that plays a video in a Modal when a thumbnail gets clicked. This only works with the first video mentioned in the html, so I'm trying to use js to grab the particular video whos thumbnail is clicked on.
I have set up a variable in the js called vidcode, and gave it a value of the first video's address (rLdpnu2dDUY) or whatever it's called. I then set up a value 'start' for the link part before, and 'end' for the link part after. Now I have "showVideo = start + vidcode + end" and then innerHTML = showVideo, which works no problems.
So far the injection part works. My problem now is passing the address of the clicked thumbnail into the vidcode variable to play the corresponding video. I have looked on SO, w3, and Google. I have 6 different tries and none work fully.
I can create a link which
- Sets the variable, but then does not call the script.
- Calls the script but does not pass on the variable.
- Click one thumb to set the variable then another thumb to call the script. That one will then work but it's an extra step. At least with this one I know that the variable is being set..
<!--== Standard button but requires var vidcode to be preset in the Modal script ==-->
<img src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg">
<!--== Add onClick to trigger a mini-script which sets the var vidcode early ==-->
<script>function hDSansxhArU(){var vidcode = 'hDSansxhArU';}</script>
<!--== Adding the javascript directly to the link code, yet it does not trigger the Modal script ===-->
<!--== Adding the javascript directly to the link code, to trigger a mini-script, to then call the modal ===-->
<script>function buttt(){var vidcode = 'duBjWlIzpzQ'; modalviewer();}</script>
<!--== Use the video's code as an id, then calling that id immediately and setting it to var vidcode ==-->
<script>
document.getElementById('hDSansxhArU').onclick = function() {
var vidcode = 'hDSansxhArU';
modalviewer()
};
</script>
Spots are commented out when trying something else
function modalviewer(){ //This function usually isn't here
var start = '<iframe width="840" height="472" src="https://www.youtube.com/embed/';
var end = '" frameborder="0" encrypted-media></iframe>';
//var showVideo = start + vidcode + end;
// This part works fine when vidcode gets a value
document.getElementById("button").addEventListener("click", function() {
document.querySelector(".theVideo").innerHTML = showVideo;
document.querySelector(".bg-modal").style.display = "flex";
});
document.querySelector(".bg-modal").addEventListener("click", function() { //.bg-modal to make the surrounding clickable
document.querySelector(".bg-modal").style.display = "none";
document.querySelector(".theVideo").innerHTML = "";
});
};
Expected results:
Click a link and have either
- set that address to variable 'vidcode', or
- set the address gobbledegook to 'vidcode' from here
and either have the modal script in a separate js file or at the bottom of the page.
As a code-newbie, I'm proud to have figured it out so far (with previous help from SO), it just frustrates me that I can only get half of this to work at a time :/.
#CTOverton provided what was needed, although everyone else and in Stop/Pause video when Modal is closed (not using $ sign) contributed with everything that they got me to look up as well. #Phoenix1355 actually started me on the right path despite me not posting any code at all, in turn leading me to learn so much in very little about Javascript and HTML.
This has been plaguing me for at least a week (I've lost track of time making this website), researching, getting other setups, trying overly-complicated setups, being told it can only be done by paying for a hosting plan or having to use Wordpress.. And this Console.log output, sooo helpful omg. Thank you everyone who contributed!
Here is the finished code:
<html>
<head>
<link href="http://www.jolanxbl.ca/snips/modal.css" rel="stylesheet" />
</head>
<body>
<center>
<br><br><br><br><br>
<!--List of videos-->
<img data-vidcode="rLdpnu2dDUY" src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg" width="200px">
<img data-vidcode="hDSansxhArU" src="https://img.youtube.com/vi/hDSansxhArU/hqdefault.jpg" width="200px">
<img data-vidcode="duBjWlIzpzQ" src="https://img.youtube.com/vi/duBjWlIzpzQ/hqdefault.jpg" width="200px">
</center>
<!-- Modal Section 1 -->
<div class="bg-modal">
<div class="modal-content">
<div class="close">+</div>
<div class="theVideo">
<iframe width="840" height="472" src="https://www.youtube.com/embed/rLdpnu2dDUY" frameborder="0" encrypted-media; picture-in-picture allowfullscreen></iframe>
</div>
</div>
</div>
<script>
let vidcode = 'rLdpnu2dDUY';
// Get all elements with classname 'thumbnail'
let thumbnails = document.getElementsByClassName('thumbnail');
// Loop for every element with class
Array.from(thumbnails).forEach(function(element) {
element.addEventListener('click', thumbnailClicked);
});
function thumbnailClicked(event) {
// Event is mouse click event
// target is the img (as that is what you click on)
// dataset is the data attributes of img
vidcode = event.target.dataset.vidcode;
console.log('vidcode: ', vidcode)
//document.querySelector(".gridContainer").addEventListener("click", function() {
document.querySelector(".theVideo").innerHTML = '<iframe width="840" height="472" src="https://www.youtube.com/embed/' + vidcode + '" frameborder="0" encrypted-media></iframe>';
document.querySelector(".bg-modal").style.display = "flex";
}
document.querySelector(".bg-modal").addEventListener("click", function() { //.bg-modal to make the surrounding clickable
document.querySelector(".bg-modal").style.display = "none";
document.querySelector(".theVideo").innerHTML = "";
});
</script>
</body>
</html>
Based on your description I think you are looking for something along the lines of the "data attribute". Data attributes are custom attributes you can assign to any DOM element that contain essentially whatever you want.
In you case if you have a page with lots of thumbnails and you want a specific action to happen when you click on a specific thumbnail, your best bet is if you store that unique identifier (the video id, or are you put it vidcode) on the element you are clicking on.
This can be done like this:
<body>
<!--List of videos-->
<img data-vidcode="rLdpnu2dDUY" src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg">
<img data-vidcode="example2" src="img2.jpg">
<img data-vidcode="example3" src="img3.jpg">
<script>
let vidcode = 'rLdpnu2dDUY';
// Get all elements with classname 'thumbnail'
let thumbnails = document.getElementsByClassName('thumbnail');
// Loop for every element with class
Array.from(thumbnails).forEach(function(element) {
element.addEventListener('click', thumbnailClicked);
});
function thumbnailClicked(event) {
// Event is mouse click event
// target is the img (as that is what you click on)
// dataset is the data attributes of img
vidcode = event.target.dataset.vidcode;
console.log('vidcode: ', vidcode)
}
</script>
</body>
Try passing the vidcode as an parameter for modalviewer function and then use the value.
function modalviewer(vidcode){
var start = '<iframe width="840" height="472" src="https://www.youtube.com/embed/';
var end = '" frameborder="0" encrypted-media></iframe>';
var showVideo = start + vidcode + end;
document.querySelector(".theVideo").innerHTML = showVideo;
};
<div class="theVideo"></div>
Click
<script>
document.getElementById('hDSansxhArU').onclick = function() {
var vidcode = 'hDSansxhArU';
modalviewer(vidcode)
};
</script>

Wrong increment and decrement in javascript

As it's understandable from the code, I'm trying to create a simple img gallery.
I'm currently facing a calculation problem; if you run the snippet performing these actions you'll see what's wrong in the console log:
clicking on an img you'll get the id of the current clicked id
if you click next the first number it prints out is the same of the clicked id
but if you click now prev you'll see that actually the value was correct 'cause it prints the incremented number and you need to clicks to decrement
if you click now on another img you'll get the id of the new clicked div
but if you click now prev or next it performs the increment or decrement two times and it seems as the previous variable $ph_id is not overwritten by the new id
Can someone please explain me where the problem comes from? 'Cause I thought the code was written right but apparently I'm missing something.
[EDIT] I put the $('#next').click(function () and the $('#prev').click(function () outside of the $('.venus-div').click(function () and the problem at points 4. and 5. are now solved
$(document).ready(function () {
$('.venus-div').click(function () {
$this = $(this);
$ph_id = $this.attr('id');
console.log('Current id: ' + $ph_id);
});
$('#next').click(function () {
$next_id = $ph_id++;
console.log('Next id: ' + $next_id);
});
$('#prev').click(function () {
$prev_id = $ph_id--;
console.log('Prev id: ' + $prev_id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="venus-div" id="1" data-image="../img/bv.jpg">
<img src="../img/thumb/bv_thumb.jpg" class="venus-thumb">
</div>
<div class="venus-div" id="2" data-image="../img/islamuj.jpg">
<img src="../img/thumb/islamuj_thumb.jpg" class="venus-thumb">
</div>
<div class="venus-div" id="3" data-image="../img/vertical.jpg">
<img src="../img/thumb/vertical_thumb.jpg" class="venus-thumb">
</div>
<div class="venus-div" id="4" data-image="../img/pano.jpg">
<img src="../img/thumb/pano_thumb.jpg" class="venus-thumb">
</div>
<p id="prev">BACK</p>
<p id="next">NEXT</p>
$next_id = $ph_id++; sets $next_id to the current value of $ph_id and then increments $ph_id by one. If you want the increment to happen first, you can place the ++ before the variable like so:
$next_id = ++$ph_id;
With this, $next_id will be equal to the incremented $ph_id.
The same applies to --:
$prev_id = --$ph_id;
I think its because you are creating and binding every click a new click event in next and prev, and its triggering multiple times due to this multiple binding. You can either off these events or bind them outside the venus-div click function (making ph_id, next_id and prev_id global vars inside document ready.
I cant write coding from mobile, if you need i'll update it later :)

deactivate ONE button/thumb of a list

I have a video array, and then a list of thumbs that correspond to the array. When you click on one of the buttons, it needs to be deactivated for the duration of the video. I have it so that after the first click, it deactivates the whole list
$('li', '.thumbs').on('touchend click', function() {
$("#myVid").on("loadeddata", function() {
$("#bigPic").addClass("move");
$("#MyT").fadeOut(750);
});
playVideo2( $(this).index() );
$('li', '.thumbs').unbind();
});
if each item in the list is set up like this:
<li rel='1' id="first">
<div style="top:0px;">
<img src="graphics/filler.png" alt="" width="280" height="128" />
</div>
</li>
with the id being different for each, can I just put the id instead of the .thumbs, and just have it unbind or turn off itself? I know this must be inefficient, but I'm not sure how else to do it. Do I use this() somehow? If so, how?
You could make use of a global variable to check which video is playing.
//init
var currentlyPlaying = undefined;
Within your event handling part you set this variable to the ID of the clicked button.
currentlyPlaying = $(this).attr('id');
With that setup you can check the variable before doing anything in your script.
if ( !(currentlyPlaying == $(this).attr('id')) ) {
// your script
}
Alternatively, you can use the ID to unbind as you suggested, of course.
$('li', '.thumbs #' + $(this).attr('id')).unbind();

Changing the onclick

Ok so I have this
<img width="38" height="39" onclick="jreviews.favorite.add(this,{listing_id:2655})" class="imgFavoriteAdd" alt="Add to favorites" id="jr_favoriteImg2655" src="http://kingdomshopper.com/templates/jreviews_overrides/views/themes/default/theme_images/fav_add.png">
and as you can see the onclick is
jreviews.favorite.add(this,{listing_id:2655})
I need to change the onclick to
jreviews.favorite.remove(this,{listing_id:2655})
but when i do
jQuery("#jr_favoriteImg2655").attr("onclick")
onclick(event)
can i do
jQuery("#jr_favoriteImg2655").attr("onclick", "jreviews.favorite.add(this,{listing_id:2655})")
or is there a better or another way
You'll be lot better off if you remove the onclick attribute from your element and then do the following >
// Initializing >>
var first = function () { jreviews.favorite.add(this,{listing_id:2655}) };
var second = function () { jreviews.favorite.remove(this,{listing_id:2655}) };
jQuery("#jr_favoriteImg2655").bind("click", first);
and then when you want to switch >
jQuery("#jr_favoriteImg2655").unbind("click", first);
jQuery("#jr_favoriteImg2655").bind("click", second);
The usual way to do that (i.e. binding functions to events) is either bind or click:
jQuery("#jr_favoriteImg2655").click(function() {
jreviews.favorite.remove(this,{listing_id:2655});
});
Using inline JavaScript is not recommended, but anyway you can use a condition here to make sure you added this to favorite before or not. Something like this:
<img width="38" height="39" onclick="if(!jreview.favorite.exist(this)){jreviews.favorite.add(this,{listing_id:2655})}else{jreviews.favorite.remove(this,{listing_id:2655})}" class="imgFavoriteAdd" alt="Add to favorites" id="jr_favoriteImg2655" src="http://kingdomshopper.com/templates/jreviews_overrides/views/themes/default/theme_images/fav_add.png">
I'm not familiar with your API and exist is just an example

managing mousever and mouseclick events

I am trying to do something quite simple.
I have an image with a rollover. When it is clicked the onmouseout and onmouseover events are removed and the image is swaped. Up to here I got it but now I would like to add something so that when it is clicked again everything returns to the original state (swap the image again and activate onmouseover and onmouseout.
Here is the code I got so far:
<a href="#"
onMouseOut="MM_swapImgRestore();
"
onMouseOver="MM_swapImage('image','','images/image-2.jpg',1)"
onClick="
MM_swapImage('image','','images/image-3.jpg',1);
this.onmouseover=null;
this.onmouseout=null;
"
>
<img name="image" src="images/image-1.jpg" id="rond9"></a>
for my quite easy solution i would add a flag and check it before firing the mouseover and mouseout events as it it remove the unnecessary burden of attaching and detaching of events.
i.e like:
<script>var myFlag=true;</script>
<a href="#"
onMouseOut="if(myFlag === true){MM_swapImgRestore();}"
onMouseOver="if(myFlag === true){MM_swapImage('image','','images/image-2.jpg',1);}"
onClick="MM_swapImage('image','','images/image-3.jpg',1);
myFlag = !myFlag;"
>
<img name="image" src="images/image-1.jpg" id="rond9"></a>
Seeing as this was generated by a WYSIWYG editor (presumably DreamWeaver), I won't suggest a jQuery implementation, but rather something that would work without referencing jQuery. You could possibly try something like:
<script type="text/javascript">
var removeEvents = true;
function EventAttach(anchor) {
MM_swapImage('image','','images/image-3.jpg',1);
anchor.onmouseover = removeEvents ? null : new function() { MM_swapImage('image','','images/image-2.jpg',1) };
anchor.onmouseout = removeEvents ? null : new function() { MM_swapImgRestore(); };
removeEvents = !removeEvents;
}
</script>
<a href="#"
onMouseOut="MM_swapImgRestore();"
onMouseOver="MM_swapImage('image','','images/image-2.jpg',1)"
onClick="EventAttach(this);"
>
<img name="image" src="images/image-1.jpg" id="rond9"></a>

Categories

Resources