How to add css code in onmouseover="hover('')" [JS] - javascript

I can't adjust my text to be center aligned. I tried to put css code in onmouseover="hover('')" but it doesn't work. What is the get around for this?
Middle circle with id="content" that changes the tag on hover
<div id="circle">
<p id="content">
<b><span>Services</span></b>
</p>
</div>
JS Code that I included in the html tag to change content on hover
<a href="">
<div onmouseover="hover('<b>BPO</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-2">
<img src="/static/img/2.png" onmouseover="this.src='/static/img/2b.png'" onmouseout="this.src='/static/img/2.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
<a href="">
<div onmouseover="hover('<b>Web Development</b>')" onmouseout="hover('<b>Services</b>')" class="scaling" id="circle-3">
<img src="/static/img/4.png" onmouseover="this.src='/static/img/4b.png'" onmouseout="this.src='/static/img/4.png'" style="margin-top:5px;" width=100px/>
</div>
</a>
JS Code that changes the content of the <p> tag
function hover(description) {
console.log(description);
document.getElementById('content').innerHTML = description;
}
everything is working properly but I can't adjust the text to be in the center regard less of the <p> tag length .
The main question is how do i add css code in onmouseover="hover('')"
What i want it to look like
what it looks like

Your code really needed a lot of cleaning up.
You should separate the HTML, CSS and JavaScript. After doing this, debugging is SO much easier and the code is much simpler to follow.
In addition, you had a great deal of duplication in your code. Again, using CSS and JavaScript can remove that redundancy. For example, styling is done with CSS, not HTML. Tags like <b> are deprecated and should no longer be used. By creating CSS styles that incorporate font-weight:bold and applying those styles properly, we can get rid of all the <b> and </b> tags.
// Get all DOM references:
var content = document.getElementById('content');
var cir2 = document.getElementById("circle-2");
var cir3 = document.getElementById("circle-3");
var img1 = document.getElementById("img1");
var img2 = document.getElementById("img2");
// Attach event handlers:
cir2.addEventListener("mouseover", function(){ hover('BPO') });
cir2.addEventListener("mouseout", function(){ hover('Services') });
cir3.addEventListener("mouseover", function(){ hover('Web Development') });
cir3.addEventListener("mouseout", function(){ hover('Services') });
img1.addEventListener("mouseover", function(e){ changeSource(e,'http://plumseattle.com/wp-content/uploads/2016/01/linkedin-logo.jpg') });
img1.addEventListener("mouseout", function(e){ changeSource(e, 'https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png') });
img2.addEventListener("mouseover", function(e){ changeSource(e, 'http://seeklogo.com/images/S/snapchat-logo-2D9C3E7ADA-seeklogo.com.png') });
img2.addEventListener("mouseout", function(e){ changeSource(e, 'https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png') });
function hover(description) {
//console.log(description);
content.textContent = description;
}
function changeSource(evt, source){
evt.target.src = source;
}
content > span { font-weight: bold;}
.scaling { font-weight:bold; }
.img { margin-top:5px;width:100px; }
<div id="circle">
<p id="content">
<span>Services</span>
</p>
</div>
<a href="">
<div class="scaling" id="circle-2">
<img id="img1"
src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-256.png"
class="img">
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img id="img2"
src="https://www.seeklogo.net/wp-content/uploads/2011/06/Twitter-icon-vector-400x400.png"
class="img">
</div>
</a>

Typically, if you want some element to listen to "mouseover" event, the best way to go is to use EventTarget#addEventListener. Just like this:
const node = document.getElementById('hover');
node.addEventListener('mouseover', () => {
node.innerText = `Last time mouseover'd at ${new Date()}.`;
});
So, now, you need to update children of #content and src attribute of an image under mouse cursor.
The HTML would look like this:
<p id="content">
Services
</p>
<a href="">
<div class="scaling" id="circle-2">
<img src="/static/img/2.png" />
</div>
</a>
<a href="">
<div class="scaling" id="circle-3">
<img src="/static/img/2.png" />
</div>
</a>
while JS code would look like this:
const content = document.getElementById('content');
const circle2 = document.getElementById('circle-2');
const circle3 = document.getElementById('circle-3');
circle2.addEventListener('mouseover', () => {
circle2.children[0].src = '/static/img/2b.png';
content.innerText = 'BPO';
});
circle2.addEventListener('mouseout', () => {
circle2.children[0].src = '/static/img/2.png';
content.innerText = 'Services';
});
circle3.addEventListener('mouseover', () => {
circle3.children[0].src = '/static/img/4b.png'
content.innerText = 'Web Development';
});
circle3.addEventListener('mouseout', () => {
circle3.children[0].src = '/static/img/4.png'
content.innerText = 'Services';
});
(check out this fiddle).

Related

Showing multiple images on click for multiple links

I'm trying to get 10 elements to appear when the user clicks one of five links.
I will only show two here to save time.
These 'appearing' elements need to be links in some way or another.
HTML - LINKS
<a class="toggler1" href="#!"
><h1 class="website-titles">A boring website</h1></a
<a class="toggler2" href="#!"
><h1 class="website-titles">Unoriginal.co.uk</h1></a
HTML - Appearing elements
<a class="mydiv1" href="main.html">
<div class="pop-up-1">
<img
class="mydiv1-bg"
src="images/pink-pop-up.png"
alt="pink pop up"
/>
<img
class="mydiv1-gif"
src="images/spinning-star.gif"
alt="animated star gif"
/>
</div>
</a>
<a class="mydiv2" href="main.html">
<div class="pop-up-2">
<img
class="mydiv2-bg"
src="images/black-pop-up.png"
alt="black pop up"
/>
<img
class="mydiv2-gif"
src="images/stars.gif"
alt="animated star background"
/>
<h1 class="mydiv2-text">
CLICK HERE TO RE-INVIGORATE YOUR WEB SURFING EXPERIENCE!!!
</h1>
</div>
JS -
This is my JS for one link, copy and pasted 2 times for convenience sake (in the real code it's 5 times for 5 links), with the elementToClick set to different classes (toggler1,toggler2... etc) within each tag. If I copy and paste this again, with another elementToShow (mydiv2 for example), this doesn't work - only one of the elements will appear
<script>
var elementToClick = document.querySelector(".toggler1");
var elementToShow = document.querySelector(".mydiv1");
if (elementToClick) {
elementToClick.addEventListener("click", showElement);
}
function showElement() {
elementToShow.classList.add("show");
}
</script>
<script>
var elementToClick = document.querySelector(".toggler2");
var elementToShow = document.querySelector(".mydiv1");
if (elementToClick) {
elementToClick.addEventListener("click", showElement);
}
function showElement() {
elementToShow.classList.add("show");
}
</script>
CSS
/* POP UP 1 */
.mydiv1 {
display: none;
}
.mydiv1.show {
display: block;
}
/* POP UP 2 */
.mydiv2 {
display: none;
}
.mydiv2.show {
display: block;
}
Thank you for looking at this mess, I am very new to Javascript and I'm sure I'm making this unnecessarily complicated for myself. If anyone can tell me how to get this working it would be greatly appreciated! Thanks!
In your Javascript code, in the showElement, use elementToShow.classList.toggle("show"); instead of elementToShow.classList.add("show");.
var elementToClick = document.querySelector(".toggler1");
var elementToShow = document.querySelector(".mydiv1");
if (elementToClick) {
elementToClick.addEventListener("click", showElement);
}
function showElement() {
elementToShow.classList.toggle("show");
}
var elementToClick = document.querySelector(".toggler2");
var elementToShow = document.querySelector(".mydiv1");
if (elementToClick) {
elementToClick.addEventListener("click", showElement);
}
function showElement() {
elementToShow.classList.toggle("show");
}
/* POP UP 1 */
.mydiv1 {
display: none;
}
.mydiv1.show {
display: block;
}
/* POP UP 2 */
.mydiv2 {
display: none;
}
.mydiv2.show {
display: block;
}
<a class="toggler1" href="#!"
><h1 class="website-titles">A boring website</h1>
</a>
<a class="toggler2" href="#!">
<h1 class="website-titles">Unoriginal.co.uk</h1>
</a>
<a class="mydiv1" href="main.html">
<div class="pop-up-1">
<img
class="mydiv1-bg"
src="images/pink-pop-up.png"
alt="pink pop up"
/>
<img
class="mydiv1-gif"
src="images/spinning-star.gif"
alt="animated star gif"
/>
</div>
</a>
<a class="mydiv2" href="main.html">
<div class="pop-up-2">
<img
class="mydiv2-bg"
src="images/black-pop-up.png"
alt="black pop up"
/>
<img
class="mydiv2-gif"
src="images/stars.gif"
alt="animated star background"
/>
<h1 class="mydiv2-text">
CLICK HERE TO RE-INVIGORATE YOUR WEB SURFING EXPERIENCE!!!
</h1>
</div>
</a>
Wrap all the elements you want to show in a div tag. For example:
<div id="elementToShow">
<a class="mydiv1" href="main.html">
.....
</div>
In your js select that enclosing element
var elementToShow = document.querySelector("#elementToShow");
The problem is in JavaScript part. You have multiple script tags, each of which have elementToClick and elementToShow. When you define elementToClick in the second (or any other) script tag, the previous ones are being overwritten. You only have one elementToClick and one elementToShow, instead of five. The same is true for all the other variables and functions (showElement).
Another piece of advice, try to use reusable code and try to never copy and paste code, like you did here. You can define one function:
function showElement(elementToShow) {
elementToShow.classList.toggle("show");
}
Then you can call this function for each of five elements:
let elements = [
{toggler: 'toggler1', div: 'div1'},
{toggler: 'toggler2', div: 'div2'},
...
];
for (let el of elements) {
let toggler = document.querySelector(`.${el.toggler}`);
let div = document.querySelector(`.${el.div}`);
toggler.addEventListener('click', () => showElement(div)); // add a click listener with a corresponding div
}
Hope this helps!

Javascript button slideshow

I am new to the javascript programming so can someone help me.
This is my code
var button = document.getElementsByTagName('button')[0];
var pic = document.getElementsByTagName('img')[0];
button.addEventListener('click', colorIt, false);
function colorIt(e) {
pic.innerHTML="src=/'https://picturejs.org/adv/banner.jpg\' width=\'400px\' height=\'150px\'>";
}
<div id="picture">
<img src="" id="picture" style="display:none;">
</div>
<button id="button">Click Me</button>
Change your colorIt function to the following. You need to set the src and then set the display to block. You might also want to move the height and width to CSS.
function colorIt(e) {
pic.src='https://picturejs.org/adv/banner.jpg';
pic.width = 400;
pic.height = 150;
pic.style.display = "block";
}
function fillIt(e) {
pic.innerHTML="src=/'https://picturejs.org/adv/banner.jpg\' width=\'400px\' height=\'150px\'>";
}
The Source for the image in JavaScript is invalid. You used HTML hyperlinks in JS.
.innerHTML modifies the content between the opening and closing tags (<div>THIS</div>), not the content of the tag itself (<div THIS></div>).
You can modify the tags attribute using setAttribute or by setting a property directly:
var button = document.getElementsByTagName('button')[0];
var pic = document.getElementsByTagName('img')[0];
button.addEventListener('click', colorIt, false);
function colorIt(e) {
pic.src='https://picturejs.org/adv/banner.jpg'
pic.width='400px'
pic.height='150px'
}
<div id="picture">
<img src="" id="picture" style="display:none;">
</div>
<button id="button">Click Me</button>
You were on the right track. However, you need to set each property in JS.
ALso I could not get picturejs.org to load so I placed a picsum pic in there instead.
var button = document.getElementsByTagName('button')[0];
var pic = document.getElementsByTagName('img')[0];
button.addEventListener('click', colorIt, false);
function colorIt(e) {
pic.src='https://picsum.photos/150/400'
pic.width='400'
pic.height='150';
pic.style.display='block';
}
<div id="picture">
<img src="" id="picture" style="display:none;">
</div>
<button id="button">Click Me</button>
Please try the below code:
function fillIt(e) {
pic.style.display = "block";
pic.src ="https://libertycity.net/uploads/download/gta5_lamborghini/thumbs/4qhllsfhd8fk9bm4mf36761u37/15205818409903_63e23c-pgta535987529.jpg";
}
You need to add the root of your image in , for example depeding on where you have the image downloaded in your PC.
Hope this helps !

Replace a smaller image with a larger one (after the larger image loads)

I have a few images of superheroes. These are in divs along with much larger images of astronomical objects. These larger images take a while to load. I want the astronomical images to replace the superhero images after they've loaded.
Here's what I have so far: https://jsfiddle.net/vmpfc1/5typ7pnp/1/
HTML:
<body>
<div class="image-wrapper">
<div class="pix"style="background: url('http://baltimorepostexaminer.com/wp-content/uploads/2012/07/spider-man2_pole_4681.jpg'); height:200px;width:200px;">
</div>
<div class="true-image" style="background: url('http://m1.i.pbase.com/o9/27/876727/1/151851961.JlvdQ9xW.GreatCarinaKeyholeandRedHoodNebulae3454x2566pixelsimproved3.jpg')"></div>
</div>
<div class="image-wrapper">
<div class="pix"style="background: url('https://upload.wikimedia.org/wikipedia/en/7/75/Comic_Art_-_Batman_by_Jim_Lee_%282002%29.png'); height:200px;width:200px;">
</div>
<div class="true-image" style="background:url(' https://www.nasa.gov/sites/default/files/706439main_20121113_m6triptych_0.jpg')"></div>
</div>
</body>
js:
setTimeout(function () {
$('.true-image').attr('style').on('load', function () {
$('.pix')({
'background-image': 'url(' + $(this).attr('src') + ')'
});
});
}, 0);
css:
.true-image {
display : none;
}
I am a javascript newbie -- is there a decent way to make the larger space images replace the superhero placeholders?
Is there an easier way to do this in HTML5?
Edited Answer to reflect changes:
<div style="background-image: url('https://i.imgur.com/sOcRl3M.jpg'); height:400px;width:400px" rel="https://i.imgur.com/xr7CRQo.jpg">
</div>
<div style="background-image: url('https://i.imgur.com/1m0NwgN.png'); height:400px;width:400px" rel="https://i.imgur.com/nlFPkc4.jpg">
</div>
Then you can have jQuery to loop through all images which has a rel attribute. 2 or 2,000 images, it does not matter.
$('div[rel]').each(function() {
var rel = $(this).attr('rel');
var self = $(this);
var img = new Image();
$(img).load(rel, '', function() {
self.css('background-image', 'url('+rel+')');
});
});
You can see it working here: https://jsfiddle.net/83zLumuk/4/

If image width is less than X, add class

As the title suggests, I'm looking to have a little bit of jQuery - if an image is less than a defined width, it adds a class a certain element. This, for me, seems pretty easy but for some reason it's not working.
$(document).ready(function() {
var image = $('.work-each img');
if (image.width() < 500) {
$('.work-text').addClass('work-text-small');
}
});
This, should, add a class 'work-text-small' to the element 'work-text' if the image found under each .work-each is less than 500px.
Example of HTML (for each)
<div class="work-each">
<div>
<img src=""/>
<div class="work-text">
<p>Title</p>
<p>Text</p>
</div>
</div>
</div>
<div class="work-each">
<div>
<img src=""/>
<div class="work-text">
<p>Title</p>
<p>Text</p>
</div>
</div>
</div>
<div class="work-each">
<div>
<img src=""/>
<div class="work-text">
<p>Title</p>
<p>Text</p>
</div>
</div>
</div>
Thanks,
R
Use load instead, when DOM is ready only img tag is defined but the image isn't loaded yet. Its size comes when it's fully loaded
$(window).load(function () {
var image = $('.work-each img');
if (image.width() < 500) {
$('.work-text').addClass('work-text-small');
}
});
However as #rdck pointed if there are more images with class=".work-each img" code won't work so in that case you go trough each image and apply the class
$(window).load(function () {
var image = $('.work-each img');
image.each(function () {
var that = $(this);
if (that.width() < 500) {
that.next('div.work-text').addClass('work-text-small');
}
})
});
If you get dimensions using server code and set class accordingly, there would be no need to wait for image to load and css would immediately take effect as soon as html exists

jQuery code refactoring help needed

An update to before, here's what I'm dealing with:
<body>
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<div class="thumb" id="carrotThumb"> <img id="showCarrot" class="imgThumb" src="img/carot.jpg" onClick=setupVeg("showCarrot", "carrotBig") /> </div>
<div class="hidden" id="carrotBig"> <img class="imgBig" src="img/carot.jpg" /> </div>
<div class="thumb" id="brocThumb"> <img id="showBroc" class="imgThumb" src="img/brocoli.jpg" onClick=setupVeg("showBroc", "brocBig") /> </div>
<div class="hidden" id="brocBig"> <img class="imgBig" src="img/brocoli.jpg" /> </div>
</div>
<!-- end thumbs container -->
<script>
var active = "";
function setupVeg(thumbVeg, hiddenVeg) {
$("#" + thumbVeg).click(function() {
if (active != hiddenVeg) {
$("div.hidden").hide("fast");
$("#" + hiddenVeg).show("fast", function() {});
active = hiddenVeg;
}
else {
$("div.hidden").hide("fast");
active="";
}
});
}
$("div.hidden").click(function () {
$("div.hidden").hide("fast");
isAnyBig=false;
});
</script>
</body>
This code is not working unfortunately. I have borrowed from suggested solution below.
Would be nice if it did work!
Any suggestions, most welcome.
I don't think you need any of the flags or the if conditions really. I think your logic is:
toggle carrotBig whenever showCarrot
is clicked.
hide div.hidden whenever showCarrot is clicked.
So all you need is:
$("#showCarrot").click(function () {
$("#carrotBig").toggle("fast");
$("#div.hidden").hide();
});
.toggle will handle one of your flags (isCarrotBig) and .hide() won't do anything if div.hidden is already hidden, so that takes care of your isAnyBig flag.
Now.. let's make that work with broc as well...
function setupVegetable(showId, toggleId) {
$("#" + showId).click(function () {
$("#" + toggleId).toggle("fast");
$("#div.hidden").hide();
});
}
setupVegetable("showCarrot", "carrotBig");
setupVegetable("showBroc", "brocBig");
If you're interested, you can refactor it FURTHER so you don't need to supply the IDs for each of the vegetables. I'll need to see your HTML markup though.
Ok I'll post a new answer in response to the edit.
Points worth noting:
Removed divs surrounding the imgs - they are unnecessary and complicate the relationship between the thumnnails and the large images.
Removed onclick attribute from within HTML - you will be attaching the event handlers in the JS so this is not needed.
Since the relationship between the thumbnails and the large images is quite obvious (the large images is just the next element) you don't need IDs to identify ANY of them. All you need is a class on the thumbnails.
Since we're not using IDs, only classes, you can add as many vegetables as you want without touching the JS
Your code modified:
<body>
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<img class="imgThumb" src="img/carot.jpg" />
<img class="imgBig hidden" src="img/carot.jpg" />
<img class="imgThumb" src="img/brocoli.jpg" />
<img class="imgBig hidden" src="img/brocoli.jpg" />
</div>
<!-- end thumbs container -->
<script>
$("#thumbsContainer .imgThumb").click(function () {
var thisImgBig = $(this).next();
// Hide all imgBigs, except for this one
$("#thumbsContainer .imgBig").not(thisImgBig[0]).hide();
// Toggle this imgBig
thisImgBig.toggle();
});
$("#thumbsContainer .imgBig").click(function () {
// Hide this imgBig
$(this).hide();
});
</script>
</body>
create a function and reuse it....something like:
/**
* document here....
*/
var toggleElements = function() {
// your code here
}
and then
$("#whatever").click(toggleElements);
Personally I would suggest creating a simple jQuery plugin. Something like so:
(function($){
$.fn.big = function(options) {
var defaults = {
target: '#carrotBig',
};
var options = $.extend(defaults, options);
return this.each(function() {
$(this).click(function () {
isBrocBig=false;
if (isCarrotBig == false && isAnyBig == false) {
$(options.target).show("fast", function() {});
isCarrotBig=true;
isAnyBig=true;
}
else if (isCarrotBig == true) {
$(options.target).hide("fast");
isCarrotBig=false;
isAnyBig=false;
}
else if (isCarrotBig == false && isAnyBig == true) {
$("div.hidden").hide("fast");
$(options.target).show("fast", function() {});
isCarrotBig=true;
}
else {
$("div.hidden").hide("fast");
isCarrotBig=false;
isAnyBig=false;
}
});
});
};
})(jQuery);
Then you just call it with something like so:
$("#showCarrot").big({target: '#carrotBig'})
Your next step should be to investigate whether you can get rid of the global variables or not.
Ok I have found a neat(ish) sollution, dependent on each hidden DIV being the .next() one. If it isn't it won't work but should be fine generally though. Hacked!
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<div class="thumb" id="carrotThumb"> <img id="showCarrot" class="imgThumb" src="img/carot.jpg" /> </div>
<div class="hidden" id="carrotBig"> <img class="imgBig" src="img/carot.jpg" /> </div>
<div class="thumb" id="brocThumb"> <img id="showBroc" class="imgThumb" src="img/brocoli.jpg" /> </div>
<div class="hidden" id="brocBig"> <img class="imgBig" src="img/brocoli.jpg" /> </div>
</div>
<!-- end thumbs container -->
<script>
var active = "";
$("div.thumb").click(function() {
var thumbVeg = $(this).attr("id");
var hiddenVeg = $(this).next().attr("id");
setupVeg(thumbVeg, hiddenVeg);
});
function setupVeg(thumbVeg, hiddenVeg) {
if (active != hiddenVeg) {
$("div.hidden").hide("fast");
$("#" + hiddenVeg).show("fast", function() {});
active = hiddenVeg;
}
else {
$("div.hidden").hide("fast");
active="";
}
}
$("div.hidden").click(function () {
$("div.hidden").hide("fast");
});
</script>

Categories

Resources