Hello I am trying to write coding for my website using Javascript and HTML. I have images on my website that I would like to have pop up or float on the side of the screen when you have your mouse over the link. I know I need to use onmouseover for this in the HTMl but I am having a lot of trouble understand Javascript and how to make this happen. The book I am using says to make add a statement to the function I made to set the value of the HTML code for the element with pix to the text
are file and desc already in javascripts language? does it know what those mean or do I need to add cariables for them and if so how do I do that?
I know it wants the file value to be the file name and the desc to be the text in the alt section of my HTML.
this is the coding that I made.
function switchPix(file, desc){
document.getElementById("pix").innerHTML=("<img src=\"images/file.jpg\" width\"480\" height=\"270\" alt=\"desc\" />");
}
I noticed that a lot of the ways everyone was refering to the image was with http but the image i have is just an image file like museum.jpg that I am suppose to be taking from a folder and putting into the website. can I just reference it like normal? "
If your images are part of your style and not part of critical content use them as background images and change them with css (img:hover for example). For effects use transitions and animations in css. It's 2016 and they are pretty good supported nowadays. This year I have moved as much as possible UI effects into CSS.
Solution for your question in pure js.
//First of all learn more about concatenation.
function switchPix(file, desc){
document.getElementById("pix").innerHTML=('<img src="' + file + '" width="480" height="270" alt="' + desc + '" />');
}
//Place first pic you want people to see
switchPix("firstPicURL", "My alt");
var pix = document.getElementById("pix");
//Use second pic for mouseover
pix.addEventListener('mouseover', function(){
switchPix("secondPicURL", "My alt");
}, false);
//Use firstPic for mouseout
pix.addEventListener('mouseout',function() {
switchPix("firstPicURL", "My alt");
},false)
I think the main problem is the concat you're using
function switchPix(file, desc){
document.getElementById("pix").innerHTML=('<img src="' + file + '" width="480" height="270" alt="' + desc + '" />');
}
switchPix("https://http.cat/100", "Continue");
https://jsfiddle.net/coins5/vu80586x/
As you have tagged jquery, I've taken the liberty to use it.
Below is an example on how to do this using jquery, I've thrown in a couple comments along the way to help explain what's going on
Edit: Note that it does show the image in fullsize, but you will have to scroll down to see it, I've made a commented javascript where I hope you'll take your time to read the comments and try to understand what's going on, but you'll be the one to style it to your needs
// The dollar sign is the object which contains everything related to jquery
// If you get an error about it not finding jquery, make sure you have the jquery script reference in the html.
// $("css selecter") - In this clase the class "picture"
// hover has 2 arguments, first is the function to call when your mouse moves in above an element
// 2nd is when your mouse leaves the lement
$(".picture").hover(function() {
// "this" is the element that is hovered above
// $(this).attr(propertyName) returns a property from "this"
// In the snippet you included, you added the the names of the variables as string literals
// That means if we do something like this
// var src = "image.jpg";
// var img1 = "<img src=\"src\" >";
// var img2 = "<img src=\"" + src + "\" >";
// img1 is now => <img src="src" />
// img2 is now => <img src="image.jpg" />
// Be sure to understand what's going on in these 5 lines above, I do believe that's what went wrong in your own script.
$("#pictureDisplayContainer").html("<img src=\"" + $(this).attr("data-displaySrc") + "\" />");
},
function() {
$("#pictureDisplayContainer").html("");
});
.picture {
display: block;
max-width: 100px;
margin-bottom: 10px;
}
#pictureDisplayContainer > img {
display: block;
max-width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Out of pure laziness, I've used the same image for thumbnail and full-size, I recommend having 2 different pictures which are both scaled to match the purpose.</p>
<img class="picture" src="http://cdn.artobserved.com/2014/02/Andisheh-Avini-Marianne-Boesky-Gallery-8.jpg" data-displaySrc="http://cdn.artobserved.com/2014/02/Andisheh-Avini-Marianne-Boesky-Gallery-8.jpg" />
<img class="picture" src="http://www.wentrupgallery.com/media/gallery.jpg" data-displaySrc="http://www.wentrupgallery.com/media/gallery.jpg" />
<div id="pictureDisplayContainer"></div>
Including a sample snippet to play around with.
We have created a sample HTML page with few links and the idea is to show the relevant image based on the action (here I am including click action / event; it can be changed to anything based on your requirement) on those links.
To answer the questions:
I am having a lot of trouble understand JavaScript and how to make
this happen
As stated, we have included an handler to the click event to the element a. Upon the action (which is click), the handler would be called with the parameters which we have passed. In this case - a file (an image) and description (description of the image).
function switchPix(file, desc) {
// construct the HTML
var html = "<img src='" + file + "' width='480' height='270' alt='" + desc + "' />";
// Find the element and set as it's inner HTML
document.getElementById("pix").innerHTML = html;
}
.navlist {
list-style-type: none;
}
.navlist li {
display: inline-block;
padding: 20px;
background-color: #F3F3F3;
}
.navlist li a {
text-decoration: none;
color: #76432a;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>My Website</title>
</head>
<body>
<div class="nav">
<ul class="navlist">
<li>
<a href="#" onclick='switchPix("https://upload.wikimedia.org/wikipedia/commons/b/bf/Bucephala-albeola-010.jpg", "Duck");'>Duck</a>
</li>
<li><a href="#" onclick='switchPix("https://upload.wikimedia.org/wikipedia/commons/0/08/South_Shetland-2016-Deception_Island%E2%80%93Chinstrap_penguin_%28Pygoscelis_antarctica%29_04.jpg", "Penguin");'>Penguin</a>
</li>
<li><a href="#" onclick='switchPix("https://upload.wikimedia.org/wikipedia/commons/b/bb/Kittyply_edit1.jpg", "Cat");'>Cat</a>
</li>
</ul>
</div>
<div id="pix">
</div>
</body>
</html>
I know it wants the file value to be the file name and the desc to be
the text in the alt section of my HTML.
The JavaScript function can be constructed and invoked based on our choice. Coming to this case, we are giving an image element a source (file) and alt(description; when the image cannot be loaded, we have to at least show what we intended).
Related
below is my code
<img src="1.gif"></i>
<img src="2.gif">
as shown in the above code when user clicks on smiley image it changes the value of text area #chat_textarea values are different for different smiley images,above code works fine... but what if i have more then 100 smileys? is there any way i can change the value of chat_textarea dynamically...? because to load images Iam just for loop which loads all images 1 to given number...
Updated:Hi all I know that we can use classname
$('.add_smile').on('click', function(){
// Prepend the ALT of the image to the textarea
$('#chat_textarea').val( $('#chat_textarea').val()+ this.alt );
});
But my question is different...i can not add alt / value to each image, it should be loaded automatically,something like fetching ;) from json file by passing id ....is there any ways to fix in that way....
Below some simpeler html.
If you want to load them dynamicly, just use your language of choice to loop through an array:
// Php
foreach($smileys as $img=>$code){ echo '<img src="'.$img.'" alt="'.$code.'" />';}
// Javascript
$.each(smileys, funcion(index,smile){
$('#smileWrap').append('<img src="'+smile.src+'" alt="'+smile.alt+'" />')
});
<img class="add_smile" src="/img1.jpg" alt=":)" />
<img class="add_smile" src="/img2.jpg" alt=":(" />
<img class="add_smile" src="/img3.jpg" alt=";)" />
$('.add_smile').on('click', function(){
// Prepend the ALT of the image to the textarea
$('#chat_textarea').val( $('#chat_textarea').val()+ this.alt );
});
jQuery doesnt care what you add the click to, the image is just fine. If you want a pointer as mouse, just css that.
Now you can use php to loop and place as many images as needed. Images are required to have an alt, that's fixed. And we can easily access it in javascript, not needing extra html (the anchor) to get that.
My jsFiddle, with auto space-add if not present
Remove unnecessary links, add a ClassName and a data-val attribute to each smiley and modify your HTML like this:
<img src="1.gif" class="smiles_btn" data-val=':#'>
<img src="2.gif" class="smiles_btn" data-val='8D'>
<img src="1.gif" class="smiles_btn" data-val=':#'>
<img src="2.gif" class="smiles_btn" data-val='8D'>
Then use this JQuery:
$('.smiles_btn').click(function(){
$('#chat_textarea').val($('#chat_textarea').val() + ' ' + $(this).data('val')).focus();
});
Check JSFiddle Demo
So I have the following JavaScript function.
var LogoUrl = function() {
document.write('views/img/common/site-logo.svg');
}
And I want to have this function used in a html img src attribute.
Here is a example though this syntax wouldn't work, it should give you an idea of what I am looking for.
<img class="site-logo" src="<script> LogoUrl() </script>" alt="Site Logo">
And hoping this would export the following in the browser
<img class="site-logo" src="views/img/common/site-logo.svg" alt="Site Logo">
What is the best approach to doing this?
You can do this with the following instead:
<script>
document.write('<img class="site-logo" src="' + 'views/img/common/site-logo.svg' + '" alt="Site Logo">');
</script>
Since the script tag is indeed a tag, you can't put it inside the attributes of another tag.
A much better approach however would be the following:
Prepare a span element for the element to appear in, and give it a specific id. This would be your HTML:
This is my image: <span id="myImg"></span>.
and this will be your jQuery code:
$(function() {
$('<img>').class('site-logo')
.attr('src', 'views/img/common/site-logo.svg')
.attr('alt', 'Site Logo')
.appendTo('#myImg');
});
Alternatively, instead of preparing a span, you could prepare the image without defining a src attribute, with the following HTML:
This is my image: <img id="myImg" class="site-logo" alt="Site Logo">.
and the following jQuery code:
$(function() {
$('#myImg').attr('src', 'views/img/common/site-logo.svg');
});
You can use jquery $(document).ready() to set the image src.
$(document).ready(function (){
$('img.site-logo').attr('src', 'views/img/common/site-logo.svg');
});
You could do this - but this makes it obstructive.
<script>document.write("<img class=\"site-logo\" src=\"views/img/common/site-logo.svg\" alt=\"Site Logo\">")</script>
It is also not very organised because it ties everything so much with the markup that you might as well just have it as markup.
You're better off doing it properly by changing the src property
var logo = document.getElementsByClassName('site-logo')[0];
logo.src = 'http://www.develop.com/Images/v3/tech-symbols/angularjs_logo.png';
demo here http://jsfiddle.net/andyw_/XxTuA/268/
If this is all you need to do - I don't think it justifies the use of a selector library or front-end framework.
I've looked around and it's been hard to find a thread that does what I want it to do. As far as I am concerned, I don't even know if it's possible. What I am looking to do is to retrieve the background image file name (especially if it is a link) when it is click. I have a script that logs all click but the last piece I need is the background-image name (file-path with name would even do) stored in the CSS file. Anyone have an idea or a solution as to how this can be done without using a div or class? Here's what I have right now:
JavaScript & HTML
<script type="text/javascript">
var arrayWithElements = new Array(); //,replaytimer;
document.onclick = clickListener;
function clickListener(e)
{
var clickedElement=(window.event)
? window.event.srcElement
: e.target,
tags=document.getElementsByTagName(clickedElement.tagName);
for(var i=0;i<tags.length;++i)
{
if(tags[i]==clickedElement)
{
if(clickedElement.tagName=="A")
{
arrayWithElements.push({tag:clickedElement.tagName,index:i});
console.log(clickedElement.baseURI,clickedElement.href,clickedElement.innerText,document.location.href,document.images.href);
}
if(clickedElement.tagName=="IMG")
{
arrayWithElements.push({tag:clickedElement.tagName,index:i});
console.log(clickedElement.baseURI,clickedElement.parentNode.href,clickedElement.innerText,document.location.href,document.getElementsById(element).src);
}
if(clickedElement.tagName=="DIV")
{
arrayWithElements.push({tag:clickedElement.tagName,index:i});
console.log(clickedElement.baseURI,clickedElement.parentNode.href,clickedElement.innerText,document.location.href,document.getElementsById(element).src);
}
if(clickedElement.tagName=="CLASS")
{
arrayWithElements.push({tag:clickedElement.tagName,index:i});
console.log(clickedElement.baseURI,clickedElement.parentNode.href,clickedElement.innerText,document.location.href,document.getElementsById(element).src);
}
}
}
}
</script>
</head>
<a id="1" href="#">trial1</a>
<a id="2" href="http://www.google.com" target="blank">google</a>
<a id="3" href="http://www.google.com">google</a>
<a id="4" href="http://www.google.com" target="_blank"><img id="image" src="untitled.jpg"/></a>
<a id="5" href="trial.html">
<input type="text" id="text-test"/>
<div id="image-link"></div>
CSS:
#image-link {
background-image:url('untitled.jpg');
width: 50px;
height:50px;
border: 1px solid #000000;
}
This is a test file that will be converted for use in the near future. Thanks
On newer browsers, you can use window.getComputedStyle(clickedElement) to find the background image property.
As per your code, just the filename or the path using JQuery in all browsers:
var withId = $("#image-link").css("background-image").split('(')[1].split(')'),
withoutId = $("img").attr("src");
// with id and css file
console.log(withId[0]);
// without id and inline style
console.log(withoutId);
Yes, as Alnitak says, use getComputedStyle, but for compatibility with more browsers check out this other question:
Get element CSS property (width/height) value as it was set (in percent/em/px/etc)
Note: I would love to be able to comment on another user's good answer instead of posting my own that is pretty much the same but with a little additional info. Unfortunately, I cannot because stackoverflow doesn't permit this for a user with less than 50 rep. So I have to post it like this instead.
I am working on a project where I need to create an embeddable button. I just want to give some code to the clients and ask them to put it where they want the button to appear on their websites. What is the best approach to it? As an example please see the following image:
I will be really thankful if someone can provide some example code.
The simplest form would be to provide a hyperlink:
Do Something
Or you could use an image button:
<a href="http://mysite.com/dosomething" title="DoSomething">
<img src="http://mysite.com/images/a.jpg" alt="DoSomething" />
</a>
These both remove dependencies on CSS and JS.
Or you can do it like suggested in your question:
<script src="http://mysite.com/scripts/embedbutton.js">
document.write('<link rel="stylesheet" href="http://mysite.com/css/embedbutton.css" />');
document.write('<div id="mybutton" onclick="DoSomething(event);">DoSomething</div>');
function DoSomething()
{
/* action code here */
}
</script>
I think that the javascript solution is the one thtat you need.
Create an javascript that will write the HTML of your button. Put the code in public/js/mybutton.js for example.
var link = 'http://yoursite.com';
var text = '<div><a href="' + link + '"><img src="'
+ link
+ '/public/images/image.png" alt="Some alt text for the image" /></a></div>';
document.write(text);
Then provide a script tag in your page for the users to embed your butscriptton.
<script src="http://yoursite.com/public/js/mybutton.js"></script>
The result will be a image with link to your site, rendered right after the script. You can use inline styling also.
I belive that this is good option when you want prevent your button styling modifications.
You could use a simple link:
Blah
and then ask your clients to embed this code into their sites. Obviously depending on the information you need to exchange between the client site and your site there could be additional parameters, javascript code, ...
Background:
I have string of html with about 10 image tags that passes through some JavaScript as a string at runtime before being injected into a containing element. The data-thumb tag of each image is slightly incorrect and needs to be altered before making it into the DOM. Here is an example:
<img src="foo_lg_db.jpg" data-large="foo_lg_db.jpg" />
<img src="bar_lg_db.jpg" data-large="bar_lg_db.jpg" />
<img src="fizz_lg_db.jpg" data-large="fizz_lg_db.jpg" />
Needs to become:
<img src="foo_tn_db.jpg" data-large="foo_lg_db.jpg" />
<img src="bar_tn_db.jpg" data-large="bar_lg_db.jpg" />
<img src="fizz_tn_db.jpg" data-large="fizz_lg_db.jpg" />
Question:
In JavaScript (jQuery is OK), how do I achieve this search and replace?
THE ANSWER:
Thanks to Mark's answer I learned that it is possible to instantiate a jQuery object before it hits the DOM so, rather than using regex, I did something like this:
var stringHtml = "<img . . .";
var div = $("<div>").html(stringHtml );
$.each(div.find('img[src]'), function () {
$(this).attr('src', $(this).attr('src').replace('_lg', ''));
});
return div.html();
$('img[data-thumb]').each(function() {
$(this).attr('data-thumb', $(this).attr('data-thumb').replace('_lg_','_tn_'));
});
Something like that in jQuery.
Sounds like a problem you should be fixing server-side if possible though.
If you give jQuery an HTML element like $('<div>') it will essentially create the HTML element for you and then you can manipulate it before inserting it into your DOM. I don't know if it will handle multiple elements, but you can create a container first (like above) and then set the content like so
$('<div>').html(yourHtml).find('img[data-thumb'])./* code above */