using javascript for changing dynamically created ASP.NET image control - javascript

I've created a table in my ASP.NET (C#,VS2010) web app whose rows and cells should be created dynamically (read from DB), I have an image in each row which is being created dynamically (in codebehind file), how can I change its image (display a hover) with mouse over? it is easy using a small JavaScript function for statically created controls, but how can it be done for dynamically created controls? can I use inline JS functions? how should I implement it?
thanks

Give the images you create dynamically a class, using their CssClass property:
// Dynamically create the image control in code behind
Image image = new Image();
Image.CssClass = "change-on-hover";
Image.ImageUrl = "image.jpg"; // Of course, this is dynamic from the database
// Save the alternative image URL in a data-attribute
Image.Attributes["data-alternate-image"] = "image-over.jpg";
parent.Controls.Add(image);
This will render each image like this:
<img src="image.jpg" class="change-on-hover"
data-alternative-image="image-over.jpg" />
Then in jQuery, you can find all the images with this class to bind the behavior:
$("img.change-on-hover")
.on("mouseover", function(e) {
// Save original src (image.jpg)
$(this).data("original-image") = this.src;
// Change src to alternative (image-over.jpg)
this.src = $(this).data("data-alternate-image");
})
.on("mouseout", function(e) {
// Change src back to original
this.src = $(this).data("original-image");
});
The data-alternative-image attribute is a nice way to store some information inside the image tag from code behind, that you can then later read in your JavaScript event handler. You can make your own data-attributes any way you like.
Some more info about the data-attribute: http://ejohn.org/blog/html-5-data-attributes/

Related

Getting hidden text field with url to update image on hover jQuery

I'm testing out some jQuery and want to update a image when hovering over a specific div or link block.
So what i was trying to do is when hovering over .test-block get the hidden text with the url and update it on .large-image-2. It can't seem to get the specific text on hover.
This is the code i have come up with:
$('.test-block').on('onmouseenter', function() {
let myUrl = $(this).find('.display-hidden').text();
$('.url').text(myUrl);
});
Im testing on this page: https://jquery-testing.webflow.io/update-image the three bottom div's and bottom picture on right is what i want to use.
Thanks in advance!
There are a few issues with your example. Mainly the way you register the event handler.
For jQuery the correct way would be $(target).on('mouseenter') - Ommit the on... part for the event you want to register when doing it through jQuery.
I would probably implement the functionality you're looking for in a less specific way and with simpler handles like the following:
$(function () {
let divs = $('[data-image-target][data-image-url]');
divs.on('mouseenter', function () {
let that = $(this)
const target = that.data('image-target')
const url = that.data('image-url')
$(target).attr('src', url);
})
divs.first().trigger('mouseenter')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=one">
Hover One
</div>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=two">
Hover Two
</div>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=three">
Hover Three
</div>
<img id="my-target-image">
Explanation:
Data attributes:
Two data attributes are getting used in my example: data-image-target and data-image-url.
Using data attributes on the elements you want the event to be fired on will make your script a bit more robust and less prone to errors, since the event registration is bound to the two attributes being present using attribute selectors for the jQuery selector $([data-image-target][data-image-url]) instead of arbitrary classnames and/or ids.
The data-image-target should have a CSS selector that points to the <img> element(s) you wish to switch the src url on, while the data-image-url should hold the url of the image you want to switch to.
The code above could even replace your existing functionality for the top 3 images on your page.
This code worked
$(function () {
let divs = $('[data-image-target][data-image-url]');
divs.on('mouseenter', function () {
let that = $(this);
const target = that.data('image-target');
const url = that.data('image-url');
$(target).attr('src', url);
});
});
Thanks to Morten for providing. With Webflow i also had to do Command + Shift + O to turn off responsiveness to the image. (when on image settings)
Attributes:
Name: data-image-target
Value: #my-target-image
And
Name: data-image-url
Value: (image url, in my case Webflow: https://uploads-ssl.webflow.com/something)
These two attributes to each hover element.
Name: id
Value: my-target-image
This to the image element to show images. (if Webflow; "my-target-image" goes in the ID field in element settings.

How to make a photo appear when clicking on another photo? Javascript, DOM

I have an assignment where I need to make a photo appear when I click on another photo. I need to put each image in an array and call on it to appear when I click on the corresponding photo. When I click on another photo, I need to remove the existing photo and replace it with another one. I need to do it with Javascript and the DOM. I'm unsure how exactly I would do this. Here's my code so far:
var photoDiv = getElementById("photos");
document.getElementById("0").addEventListener("click", function () {
var img = createElement("img");
photoDiv.appendChild(img);
})
I know it's completely wrong but I don't know what to do to fix it :(
You have to add the image source of your image.
After this line:
var img = document.createElement("img");
img.src = 'pathto/yourimg.png_or_jpg'; // You need this.
Also, it's always a good practice to use document.getElementById() (or putting the parent) instead of just getElementById().
Instead of creating a new image you can also replace only the src of the image element, something like this:
// get the image
var imgElement = document.getElementById("myImage");
// add the listener
imgElement.addEventListener("click",
function () {
// update the src of the image
imgElement.src = "https://www.w3schools.com/html/img_girl.jpg";
});
and that's all, you should not create a new element and append it to the DOM element.

How to add new image element to html href link with javascript?

I have a problem creating a new image element to this code here:
Sound Packs
Unfortunately, I do not have access to the HTML code because it belongs to a locked template of "jimdo". I can only insert CSS codes and javascript in the "head area". Is there a way to add an image element to this HTML code with javascript?
Yes, there is a way to do this using just javascript. Firstly you need to set the window.onload callback to a function. Within this function, you can then get the element you want to add the image to. Here I added the image to the element with the attribute data-link-title which is equal to "Sound Packs".
Lastly, you can use .innerHTML on this element to add the HTML you want to add within this element. Here I added a <br /> followed by an <img> tag:
document.body.onload = function() {
let soundPacks = document.querySelector('[data-link-title="Sound Packs"]');
soundPacks.innerHTML += "<br /><img src='https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a' alt='StackOverflow Logo'/>";
}
Sound Packs

Add JavaScript onClick to dynamically generated asp button

Background My page creates a list of objects based on rows of an SQL Database. For each object, a DIV is dynamically generated that contains a few items including a LinkButton and a further child DIV that is initially hidden. I want the link button to toggle the child DIV's hidden property. The JavaScript is not dynamically generated and is included in the ASPX page.
Problem I don't know how to make this generated LinkButton fire JavaScript that is included in the ASPX page and pass in the correct DIV's ID.
I'm guessing I need to add an attribute to the button like so:
myButton.Attributes.Add(reference to JS function + parameter of DIV's ID)
Maybe like:
myButton.Attributes.Add("onclick", "Show_Hide_Display('"<%="' +idString+ '".ClientID%>"')");
Where the button is given an attribute of a JS onClick handler pointing to the function "Show_Hide_Display" and a parameter of a DIV's ID that is calculated as the rendered ID. This syntax is incorrect though.
How do I write this so it calls 'Show_Hide_Display' and passes the ID of the current child DIV? All of the DIVs have the same ID apart from a number that references their row number, for example '"myDiv_" + counter.ToString'
The JavaScript I am trying to add a call to on the button:
function Show_Hide_Display(divID) {
var div = document.getElementById(divID);
var style = document.defaultView.getComputedStyle(div);
var display = style.getPropertyValue('display');
if (display == '' || display == 'block') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
}
Use the following syntax ...
myButton.Attributes.Add("onclick", "Show_Hide_Display(this.id);");
the above syntax allows to call the function with id as its parameter.
suggestion:
Try to write a common function which does not depend on generated ids of controls.
If this is not useful for your requirement, please post your code which might gives me a better idea.
If you are using jQuery, you could you jQuery delegate method.
$(document).on("click", "div.parent", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};
You need to implement getSubDivByParent according your DOM structure.
If you are not using jQuery, you need to attach event yourself. For each dynamically generated element. You need to manually add following script in your server code to register event.
... your html code ...
<script>
var elem = document.getElementById('new-created-element');
elem.addEventListener("click", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};)
</script>
My suggestion is use jquery to achieve the functionality.
My solution works if you want to toggle the immediate div for the link.just call onclientclick method to toggle the div.
in linkbutton onclientclick="Show_Hide_Display(this)"
function Show_Hide_Display(id) {
$(id).next('div').toggle();
}
I hope this helps you .. Thanks

SImple image replace using Javascript/html

Couldn't find a punctual answer for this simple task and your help is highly appreciated
We have an image we want to switch based on user's color selection.
Tried several methods, none worked.
This is the idea:
$('#YourButton').click(function() {
var oldSrc = 'images/Image1.png';
var newSrc = 'images/Image2.png';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
});
Just change the image source with javascript by clicking your button with another color
Note: it´s jquery so you have to include the js file..
Just bind a click listener to your button and change the src attribute of your image.
$('#colorButton').click( function() { //choose a new color
$('#imageIcon').attr('src', 'path/to/new/image.png'); //change the img's source
});
EDIT (response to questions):
If you want this code to apply to all of your buttons, give each of your buttons a similar class instead of an ID:
<div class="colorButton"></div>
Then you can use the following selector to apply the above click listener to all of these divs:
$('.colorButton')
Naturally, you want to change your image as simply as possible. You could map all of your colors to their corresponding image file, but as far as design goes this might get messy and unwieldy. I would create a directory that stores all of your image files (for example, /your/color/swatches) and give each of them a name consistent with their color, like 'ff0000.png' for red, '0000ff.png' for blue, etc.
Why would we do this? So that we can switch your image based on the background-color attribute of your buttons. Let's say that you have the following buttons:
<div class="colorButton" style="background-color: '#ff0000'"></div>
<div class="colorButton" style="background-color: '#0000ff'"></div>
You can use the same click listener, but it will have to be modified a bit since we are mapping the background color to an image:
$('.colorButton').click( function() {
var color = $(this).css('backgroundColor');
//(You'll need to modify your color string here)
$('#imageIcon').attr('src', 'your/color/swatches/' + color + '.png');
});
BUT this won't work yet. Since most browsers return "rgb(xx, yy, zz)" from .css('backgroundColor'), you need to convert that string into hex. This post on SO gives a more or less effective way to do so, but you'll need to modify it to fit your model where I have indicated.

Categories