Reputation: 231
A div with a data url attribute must be replaced by a link. The link must get the data-url attribute from the div. However, this should only happen with a mouseover or a click.
So this div:
<div class="thelink" data-url="https://www.example.com">The Title</div>
should become to this on mouseover or a click
<a href="https://www.example.com">The Title</a>
I tried something like this:
<script>
$(".thelink").on('click mouseover', function(){
replaceWith("<a href=\"here data-url\">The Title</a>");
});
Is this possible? Thank you very much for your time and effort.
Upvotes: 1
Views: 371
Reputation: 461
Here is how you do it:
$(".thelink").on('click mouseover', function(){
let dataURL = $(this).data('url');
$(this).replaceWith(`<a href="${dataURL}">The Title</a>`);
});
But if you need to simply open a url when clicking on a div you can do it like this:
$(".thelink").on('click', function(){
window.location.href = $(this).data('url');
});
Upvotes: 1
Reputation: 14570
You could use event delegation on dynamically added element and use mouseover
to add an a
and on mouseout
it will add the div
back again.
We also need to use a class
on our a
href
element so that we can use the same use to on mouseout
to bring back the original div
Demo
//Mouse over function
$(document).on('mouseover click', '.thelink', function() {
$(this).replaceWith($('<a class="newLink">').text($(this).text()).attr("href", $(this).data("url")));
});
//Mouse out function
$(document).on('mouseout click', '.newLink', function() {
$(this).replaceWith($('<div class="thelink">').text($(this).text()).attr("data-url", $(this).attr("href")));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="thelink" data-url="https://www.example.com">The Title</div>
Upvotes: 1